[removed] Find key and its value in JSON

后端 未结 5 598
暖寄归人
暖寄归人 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:48

    You can try this

    const data = {
    	"Records": {
    		"key": "112"
    	}
    };
    
    const data2 = {
    	"Records": {
    		"test": { "key": "512" }
    	}
    };
    
    const data3 = {
    	"Records": {
    		"test": {
    			"test2": [
    				{ "key": "334" },
    			]
    		}
    	}
    };
    
    function searchKey(obj, key = 'key') {
    	return Object.keys(obj).reduce((finalObj, objKey) => {
    		if (objKey !== key) {
    			return searchKey(obj[objKey]);
    		} else {
    			return finalObj = obj[objKey];
    		}
    
    	}, [])
    }
    
    const result = searchKey(data);
    const result2 = searchKey(data2);
    const result3 = searchKey(data3);
    console.log(result);
    console.log(result2);
    console.log(result3);

提交回复
热议问题