我在循环数组时遇到问题。也就是说,在 JavaScript 中的数组内部的对象内部。下面是我的循环,下面是我的对象。
我想检索对象的名称。请比较我的 $('#searchbox').keypress
函数和我的 var Animals_data
对象
$('#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"
}
]
}]
};
最佳答案
您可以通过[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 ...
})
<小时/>
But what if I have many objects in the array category. Each of which contains an array that I want to itterate through.
为此,您可以使用嵌套的 Array.forEach()
方法,如下所示:
animals_data.category.forEach(function(a) {
a.animalsR.forEach(function(e) {
// do something
});
});
关于javascript - 如何在javascript中的数组内部循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35870521/