0

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"
 }
 ]
 }]
};
Vyacheslav
27.3k22 gold badges124 silver badges209 bronze badges
asked Mar 8, 2016 at 14:49

1 Answer 1

1

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
 });
});
answered Mar 8, 2016 at 14:52
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, all that I needed was category[0]. But what if I have many objects in the array category. Where each object contains an array that I want to iterate through. So I dont only have the "animalsR"-array, I would have more arrays inside. I would try to make the index generic. And also have the same name for each array (animalsR for example). animals_data.category[i].animalsR.filter{ //do stuff }

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.