Marcos Belunti Marcos Belunti - 2 months ago 7
Javascript Question

Javascript array loop variable undefined

I am having a bit of trouble with a loop that reads an array:

var myStringArray = [{
"people": [{
"id": "123",
"name": "name 1"
}, {
"id": "456",
"name": "name 2"
}]
}];

var arrayLength = myStringArray.length;

for (var i = 0; i < arrayLength; i++) {
console.log(myStringArray[i].id);
}


Where am I going wrong here?

Answer

You need to iterate over the inner array(people property of the first element in the main array).

var myStringArray = [{
  "people": [{
    "id": "123",
    "name": "name 1"
  }, {
    "id": "456",
    "name": "name 2"
  }]
}];
var arrayLength = myStringArray[0].people.length;

for (var i = 0; i < arrayLength; i++) {
  console.log(myStringArray[0].people[i].id);
}


Although you can use Array#forEach method.

var myStringArray = [{
  "people": [{
    "id": "123",
    "name": "name 1"
  }, {
    "id": "456",
    "name": "name 2"
  }]
}];

myStringArray[0].people.forEach(function(v) {
  console.log(v.id);
});

Comments