[removed] Find key and its value in JSON

后端 未结 5 637
暖寄归人
暖寄归人 2021-01-14 01:12

I have a JSON object that is returned in different ways, but always has key. How can I get it?

E.g.

\"Records\": {
    \"key\": \"112\"
         


        
5条回答
  •  渐次进展
    2021-01-14 01:45

    You could use an iterative and recursive approach for getting the object with key in it.

    function getKeyReference(object) {
        function f(o) {
            if (!o || typeof o !== 'object') {
                return;
            }
            if ('key' in o) {
                reference = o;
                return true;
            }
            Object.keys(o).some(function (k) {
                return f(o[k]);
            });
        }
    
        var reference;
        f(object);
        return reference;
    }
    
    var o1 = { Records: { key: "112" } },
        o2 = { Records: { test: { key: "512" } } },
        o3 = { Records: { test: { test2: [{ key: "334" }] } } };
    
    console.log(getKeyReference(o1));
    console.log(getKeyReference(o2));
    console.log(getKeyReference(o3));

提交回复
热议问题