I want create key array which value is "str" I have following nested json:
[
{
"Attr": [
{
"power": { "p1": "str", "t3": "str" },
"light": [
{"test": "str"},
{"test2": [ { "t4": "str" }]}
]
}
]
},
{
"Attr1": [
{
"power1": { "p2": "str", "t5": "str" },
"light1": [
{ "test3": "str" },
{ "test_x": [
{ "t_x": "str" },
{ "t_y": [
{ "t_y1": "str" }
]
}
]
}
]
}
]
}
]
I want to create array of key where key value is "str",
I want get following array output:
["p1", "t3", "test", "p2", "t5", "test3", "t_x", "t_y1"]
How to create key array from nested JSON by particular value?
If you can write an recursive function that would be best for performance.
But if you want to skip the recursive calling with (for each keys in a nested object), then you can try JSON.parse
with additional parameter (callback) which will be called recursively by it. as a generic solution, I am adding a snippet (with JSON.parse
, assuming helping on writing a recursive function should not be entertained / part of this answer).
But remember, IF you are bothered about performance efficiency you should not use this as you have to stringify (may be a large object) and again parse. But, if you have a JSON string, it should be one of the best solution.
var anyObject = [
{
"Attr": [
{
"power": { "p1": "str", "t3": "str" },
"light": [
{"test": "str"},
{"test2": [ { "t4": "str" }]}
]
}
]
},
{
"Attr1": [
{
"power1": { "p2": "str", "t5": "str" },
"light1": [
{ "test3": "str" },
{ "test_x": [
{ "t_x": "str" },
{ "t_y": [
{ "t_y1": "str" }
]
}
]
}
]
}
]
}
]
function getKeys(obj, str) {
let resultArr = [];
JSON.parse(JSON.stringify(obj), (key, val) => {
if(val === str) { resultArr.push(key) }
return val;
} )
return resultArr;
}
console.log(getKeys(anyObject, 'str'))
This is not case specific, you can have all the keys if you pass another callback in JSON.parse
and also can transform the object using this (returning transformed value instead the actual value)
And if you want to use lodash to iterate the object recursively, then you can use
_.cloneDeepWith
for iterating the object recursively.
Here is a Working example:
let anyObject = [
{
"Attr": [
{
"power": { "p1": "str", "t3": "str" },
"light": [
{"test": "str"},
{"test2": [ { "t4": "str" }]}
]
}
]
},
{
"Attr1": [
{
"power1": { "p2": "str", "t5": "str" },
"light1": [
{ "test3": "str" },
{ "test_x": [
{ "t_x": "str" },
{ "t_y": [
{ "t_y1": "str" }
]
}
]
}
]
}
]
}
];
function getKeys(obj, str) {
let resultArr = [];
_.cloneDeepWith(obj, (value, key) => { value === 'str' && resultArr.push(key)});
return resultArr;
}
console.log(getKeys(anyObject, 'str'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>