I have problems while looping through an array. That is, inside an object which is inside of an array in javascript. Below is my loop and under is my object. I want retrieve the names of the objects. please, compare my $('#searchbox').keypress
function and my var animals_data
object
$('#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"
}
]
}]
};
You can get first element in array via [0]
, category
in your case is an Array
animals_data.category.animalsR.filter
// ^---- your error here, it's an array
For iterating arrays you can use 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.
For that you can use nested Array.forEach()
method, like this:
animals_data.category.forEach(function(a) {
a.animalsR.forEach(function(e) {
// do something
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.