Reputation: 4366
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.
Upvotes: 0
Views: 580
Reputation: 19372
Your nested object is strictly formatted (has name, age in all nested elements).
Also what's the reason to check that it hasOwnProperty
?
You iterate an object by keys and don't know it has iterator key
?
Why not just simply iterate the object?
var obj = {
p1: {
name: "name1",
age: "age1"
},
p2: {
name: "name2",
age: "age2"
}
};
function func1(value) {
console.log('Name:', value);
}
function func2(value) {
console.log('Age:', value);
}
for(var i in obj) {
if(typeof obj[i] != 'object')
continue;
console.log('\nOutputing:', i);
func1(obj[i].name);
func2(obj[i].age);
}
Upvotes: 1
Reputation: 6240
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
Upvotes: 1