1

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?

2
  • 2
    You're not going deep enough... myStringArray[0].people[i].id. ;) Commented Sep 21, 2016 at 9:15
  • 1
    and var arrayLength = myStringArray[0].people.length; Commented Sep 21, 2016 at 9:15

3 Answers 3

3

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);
});

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

Comments

0

Access id from object stored in myStringArray[0].

Here is the modified code:-

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

var array = myStringArray[0].people,
    arrayLength = array.length;
for (var i = 0; i < arrayLength; i++) {

    console.log(array[i].id);

}

Comments

0

because your array only haw 1 item and its people. and people don't has id property. the people contains two item that every one has their id.

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

Comments

Your Answer

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