How to get the key value from nested object

前端 未结 5 972
刺人心
刺人心 2020-12-06 15:32

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

[{
    \"type\": \"test\",
    \"id\": \"100\",
    \"values\": {
        \"name\": \"A         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 16:20

    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.

提交回复
热议问题