简体   繁体   中英

Javascript: Find key and its value in JSON

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

Eg

"Records": {
    "key": "112"
}

Or

"Records": { 
    "test": {
        "key": "512"
    }
}

Or even in array:

"Records": { 
    "test": {
        "test2": [
            {
                "key": "334"
            }
        ]
    }
}

Tried several options, but still can't figure out (

I will not write the code for you but give you an idea may be it will help, First convert JSON object in to string using

JSON.stringify(obj);

after that search for Key using indexOf() method. Extract previous '{' and Next '}' string and again cast in to JSON object. using

var obj =  JSON.parse(string);

Then

 var value = obj.key

I think this migth be solution (asuming key is always string and you don't care about res of data)

 const data = [`"Records": { "test": { "test2": [ { "key": "334", "key": "3343" } ] } }`, `"Records": { "test": { "key": "512" } }`, `"Records": { "key": "112" }`] const getKeys = data => { const keys = [] const regex = /"key"\\s*:\\s*"(.*)"/g let temp while(temp = regex.exec(data)){ keys.push(temp[1]) } return keys } for(let json of data){ console.log(getKeys(json)) } 

How can i get it?

Recursively! eg

function getKey(rec) {
    if (rec.key) return rec.key;

    return getKey(rec[Object.keys(rec)[0]]);
}

https://jsfiddle.net/su42h2et/

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)); 

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM