user4324324 user4324324 - 5 months ago 11
JSON Question

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

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.

Comments