0

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!

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

10 Comments

that is going to give you an index out of bounds exception as you never check the length of the array.
@bhspencer: No, since Javascript doesn't throw out of bounds exceptions. It will just give undefined when it gets to the end. The problem with this approach is if there is a falsy value partway through the array, it will stop and not continue past it. Using the length is much better.
@bhspencer Nope, when the for loop reaches an undefined value it stops because the second boolean (yes it's boolean) condition is not met.
I don't doubt that it will work. Just don't think it is a good idea.
@Legendary forEach (not each) is not guaranteed to be supported by all the browsers and JS engines.
|
1

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

1 Comment

Keep in mind that it's not a good idea to declare variables inside a for loop, this can lead to nasty bugs when combined with closures and variable hoisting.
1

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!

Comments

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.