我在遍历数组时遇到问题。也就是说,在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 ...
})
但是,如果我在数组类别中有很多对象怎么办。每个都包含一个我想通过的数组。
为此,您可以使用嵌套Array.forEach()
方法,如下所示:
animals_data.category.forEach(function(a) {
a.animalsR.forEach(function(e) {
// do something
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句