return 0 return 0 - 3 months ago 13
Javascript Question

How to assign sub-object to a variable in javascript?

I have a javascript object that looks like

var obj = {
p1: {
name: "name1",
age: "age1"
}
p2: {
name: "name2",
age: "age2"
}
}


I want to be able to access name and age iteratively, meaning something like this:

for (var p in obj) {
if (obj.hasOwnProperty(p)) {
func1(p.name);
func2(p.age);
}
}


However, p.name is shown as "undefined" in debugger, so are the other keys of p. I wonder if javascript allows users to assign sub-object to a new variable like in Python.

Answer

I think you're missing something there. Look:

for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
        func1(obj[p].name);
        func2(obj[p].age);
    }
}

This should work.

p only exists as a property of obj so, even inside a for-in loop, you still have to access p as a property of obj (from the loop).

If you're learning javascript, this may not be obvious but there's actually two ways to access object properties: dot notation and the square brackets notation. Using your example, obj.p1.name === obj['p1']['name].

Sometimes you need square brackets notation because you want to pass it some variable, which is what you need inside the for-in loop.

I hope this is clear. If not, you can see it working on this JSBin

Comments