Acyra
Acyra

Reputation: 16034

How to access an Object in an Object in javascript

Hi I have a "persons" Object that contains four "person" Objects

[Object, Object, Object, Object]

In turn, each these "person" Objects contain keys and values. How do I access these values in Javascript? Trying this to access their "name" field, for example, doesn't work:

for(var person in data.persons) {

    var nameList = nameList + person.name; 
}

I'm a JS newbie. Thanks!

Upvotes: 0

Views: 46

Answers (3)

Marco Bonelli
Marco Bonelli

Reputation: 69276

Since that your persons object is actually an Array, you can access it with a simple for, but iterating with an index variable, like this:

var nameList = '';
for (var i=0, person; person = data.persons[i]; i++) {
    nameList += person.name;
}

or eventually, like this:

var nameList = '';
for (var i=0; i < data.persons.length; i++) {
    nameList += data.persons[i].name;
}

What you're doing there is to iterate over the indexes, so your person variable holds an index number, not a person object:

for(var person in data.persons) {
    // person will be 0, 1, 2, 3...
    // by the way you can still do:
    nameList += data.persons[person].name;
}

Upvotes: 2

Legendary
Legendary

Reputation: 2242

Mb it because of your syntax ? Try that and show your output:

var nameList = '';
var test = {name: 'Joe'};
var persons = [test, test];
persons.forEach(function(v, i){
  console.log(v.name);
  console.log("index = " + i);
  nameList = nameList + v.name; 
});
console.log(nameList);

P.s edit and check, all ok!

Upvotes: 1

bhspencer
bhspencer

Reputation: 13560

You cannot use a for-in loop with an array. Use a for loop instead with a counter.

for (var i = 0; i < data.persons.length; i++) {
    var person = data.persons[i];
    var nameList = nameList + person.name; 
}

Upvotes: 1

Related Questions