2016-03-08 51 views
0

我在循環數組時遇到問題。也就是說,在javascript中一個數組內部的對象內。下面是我的循環,下面是我的對象。 我想檢索對象的名稱。請比較我$('#searchbox').keypress功能和我var animals_data對象如何在JavaScript中的數組內部的數組內循環?

$('#searchbox').keypress(function (e) { 
    if (e.which == 13) { 
     var search_text = $('#searchbox').val(); 
     console.log(search_text) 
     var filteredData = { 
      animalsR: animals_data.category.animalsR.filter(function(d){ 
       if (d.name.search(search_text) > -1){ 
        return true; 
       } 

       return false; 
      }) 
     }; 

     var source = $("#album-template-Reptile-result").html(); 
     var template = Handlebars.compile(source); 
     var html = template(filteredData); 
     $('#content').html(html); 
    } 
}); 

var animals_data = { 
    category : [{ 
     name : "Reptiles", 
     animalsR : [ 
      { 
       image1 : "url" , 
       image2 : "url" , 
       name : "Snake", 
       description : "text" 
      }, 
      { 
       image1 : "url", 
       image2 : "url", 
       name : "Crocodilia", 
       description : "text" 
      } 
     ] 
    }] 
}; 

回答

1

您可以通過[0]獲得第一個元素數組,category你的情況是Array

animals_data.category.animalsR.filter 
//     ^---- your error here, it's an array 

對於遍歷數組,你可以使用Array.prototype.forEach()

animals_data.category[0].animalsR.forEach(function(e){ 
    // do something ... 
}) 

但是如果我在數組類別中有很多對象會怎麼樣。其中每個包含我想要遍歷的數組。

對於您可以使用嵌套Array.forEach()方法,像這樣:

animals_data.category.forEach(function(a) { 
    a.animalsR.forEach(function(e) { 
     // do something 
    }); 
}); 
+0

謝謝你,所有我需要的是類別[0]。但是如果我在數組類別中有多個對象呢?每個對象都包含我想要遍歷的數組。所以我不只有「animalsR」 - 數組,我會有更多的數組。 我會盡量使索引通用。並且每個數組也有相同的名稱(例如animalsR)。 animals_data.category [i] .animalsR.filter { // do stuff } – knixer

相關問題