简体   繁体   English

JavaScript对象结构:如何使用“ complex.key”访问内部字段

[英]JavaScript object structure: how to access inner field with 'complex.key'

Given an object like this: 给定这样的对象:

var obj = {
"name":"JonDoe",
"gender":"1",
"address":{
    "phone":"1"
    }
}

I know you can have such things : 我知道你可以有这样的事情:

    console.log(obj['name']); // returns 'JonDoe'

My problem comes with the inner structure 'address', whose 'phone' inner field I would like to target with obj['address.phone'] but it returns instead undefined where all level 1 field return the matching value. 我的问题来自内部结构“地址”,我想使用obj['address.phone']定位其“电话”内部字段,但它返回的是undefined ,其中所有级别1字段均返回匹配值。

I am quite sure you could do it with some (de)serialisation function or any json lib, but I am am wondering if there's a smart way to list all inner structures like 'address' with no preliminary knowledge of which field I am going to target (like obj[field]). 我很确定您可以使用一些(反)序列化函数或任何json库来做到这一点,但是我想知道是否存在一种聪明的方式来列出所有内部结构(如“地址”) ,而无需我初步了解哪个字段目标 (例如obj [field])。

Do: 做:

var phone = obj.address.phone;

Bracket notation is typically used when using variables as the property name. 使用变量作为属性名称时,通常使用括号表示法。 If you know the properties, feel free to use dot notation (seen above) 如果您知道属性,请随时使用点符号(如上所示)

You can try this: 您可以尝试以下方法:

var addresses = [];

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        addresses.push(obj[key]['address']);
    }
}

console.log(addresses);

For more complex object property querying use this library linq.js - LINQ for JavaScript 对于更复杂的对象属性查询,请使用此库linq.js-LINQ for JavaScript

Update 更新

If you want to list all address phones no matter how deep they are try recursive scanning: 如果要列出所有地址电话,无论它们的深度如何,请尝试递归扫描:

var phones = [];

var scan = function(obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (key == 'address') {
                phones.push(obj[key]['phone']);
            }
            else if (typeof obj[key] === 'object') {
                scan(obj[key]);
            }
        }
    }
};

scan(obj)
console.log(phones);

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

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