Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

javascript - How to get the key value from nested object

I am having below object where I am trying to get all the id values.

[{
    "type": "test",
    "id": "100",
    "values": {
        "name": "Alpha"
    },
    "validations": []
}, {
    "type": "services",
    "validations": [{
        "id": "200",
        "name": "John",
        "selection": [{
            "id": "300",
            "values": {
                "name": "Blob"
            }
        }]
    }]
}]

Using the below code, I am getting only the first id value. Is there any way to get all the id values from the nested object without using any external module.

for (var prop in obj) {
            console.log(prop)
            if (prop === key) {
                set.push(prop);
            }
        }

Expected Output

[100,200,300]     //all id values
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a JavaScript function like below to get the nested properties:

function findProp(obj, key, out) {
    var i,
        proto = Object.prototype,
        ts = proto.toString,
        hasOwn = proto.hasOwnProperty.bind(obj);

    if ('[object Array]' !== ts.call(out)) out = [];

    for (i in obj) {
        if (hasOwn(i)) {
            if (i === key) {
                out.push(obj[i]);
            } else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
                findProp(obj[i], key, out);
            }
        }
    }

    return out;
}

Check this Fiddle for a working solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...