简体   繁体   中英

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.

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]).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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