简体   繁体   English

如何在javascript中将子对象分配给变量?

[英]How to assign sub-object to a variable in javascript?

I have a javascript object that looks like 我有一个看起来像的javascript对象

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. 但是,p.name在调试器中显示为“ undefined”,p的其他键也是如此。 I wonder if javascript allows users to assign sub-object to a new variable like in Python. 我想知道javascript是否允许用户像Python中一样将子对象分配给新变量。

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). p仅作为obj的属性存在,因此,即使在for-in循环内,您仍必须从循环访问p作为obj的属性。

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. 如果您正在学习javascript,这可能并不明显,但是实际上有两种访问对象属性的方式:点表示法和方括号表示法。 Using your example, obj.p1.name === obj['p1']['name] . 以您的示例为例, 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. 有时,您需要方括号表示法,因为您希望向其传递一些变量,这是for-in循环中所需的变量。

I hope this is clear. 我希望这很清楚。 If not, you can see it working on this JSBin 如果没有,您可以看到它正在此JSBin上运行

Your nested object is strictly formatted (has name, age in all nested elements). 嵌套对象严格格式化(在所有嵌套元素中都有名称,年龄)。
Also what's the reason to check that it hasOwnProperty ? 另外,检查它具有hasOwnProperty的原因是什么?
You iterate an object by keys and don't know it has iterator key ? 您通过键迭代对象,不知道它具有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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM