how to find the json path for a specific value using javascript
var data = {
key1: {
children: {
key2:'value',
key3:'value',
key4: value
},
key5: 'value'
}
expected result from the above data.key1.children.key3
Any help would be appreciated.
CodePudding user response:
var str = "key3"; data["key1"]["children"][str];
CodePudding user response:
This function returns all available paths in your(any) object:
Using this function you can get
["key1.children.key2", "key1.children.key3", "key1.children.key4", "key1.key5"]
function allPaths(root) {
let stack = [];
let result = [];
// checks if object
const isObject = value => typeof value === "object";
stack.push(root);
while (stack.length > 0) {
let node = stack.pop();
if (isObject(node)) {
Object.entries(node).forEach(([childNodeKey, childNodeValue]) => {
if (isObject(childNodeValue)) {
const newObject = Object.fromEntries(
Object.entries(childNodeValue).map(([cnk, cnv]) => {
return [`${childNodeKey}.${cnk}`, cnv];
})
);
stack.push(newObject);
} else {
stack.push(`${childNodeKey}`);
}
})
} else {
result.push(node);
}
}
return result.reverse();
}
Let me know in the comments if it was helpful for you