user3519144
user3519144

Reputation: 29

got undefined loop through obj array using forEach

I do console.log(entry.passengers) I got this

[{"name":"james"},{"name":"john"},{"name":"abc"}]

But why I got undefined when I used forEach?

entry.passengers.forEach(function(i,obj){
  console.log(obj.name); // undefined
});

Upvotes: 1

Views: 74

Answers (1)

Tushar
Tushar

Reputation: 87203

The first parameter to forEach is the element and second parameter is the index.

entry.passengers.forEach(function(obj, i) {
//                                ^^^  ^ Change the sequence

var arr = [{
  "name": "james"
}, {
  "name": "john"
}, {
  "name": "abc"
}];

arr.forEach(function(e, i) {
  console.log(e, i);

  document.write(e.name + '<br />');
});

Upvotes: 4

Related Questions