Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...