0

If I have a nested array as follows:

var attendees={attendees :[{name: John},{name: Terry}]}

how do I loop through the names using the forEach function? I have tried:

attendees.forEach(function(attendees){
    console.log(attendees.name):
});

but it does not loop through the subarrays and just gives me:

[{name: John},{name: Terry}]

Appreciate the help!

1
  • it should be attendees.attendees.forEach. The first is an object with a property attendees which is an array. Commented Aug 19, 2015 at 6:49

2 Answers 2

2

With another foreach when detects is an array:

attendees.forEach(function(attendee){
   if(attendee.isArray()) {
      attendee.forEach(function(subattendee) {
         console.log(subattendee):
      });
   }
});

Be carefull with the nested variable. You have the same name for de readed array and for the function asigned variable.

Good luck

Sign up to request clarification or add additional context in comments.

1 Comment

This works! With the following amendment: if(Array.isArray(attendee))
1

It should be like this :

var attendees={
attendees : [
    { name: 'John'},
    { name: 'Terry'}
]};



attendees.attendees.forEach(function(attendees){console.log(attendees.name);});

1 Comment

hmmm when I try 'attendees.attendees.forEach(function(attendees)' I get: 'Cannot read property 'forEach' of undefined' error and when I try 'if (attendee.isArray())' I get an 'undefined is not a function' error

Your Answer

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.