I'm also trying to solve this problem, the JSON path also include array, and this is the method I finally came up with:
function findValuePath(obj, value) {
// Initialize the array of results and the array of paths
let result = [];
let path = [];
// Recursive functions look up values
function searchValue(obj, value) {
for (let key in obj) {
// If the current attribute value is equal to the target value, the path is logged
if (obj[key] === value) {
path.push((Array.isArray(obj) ? `[${key}]` : `.${key}`));
result = path.slice();
path.pop();
}
// If the current property is an object or array, search recursively
else if (typeof obj[key] === 'object') {
path.push((Array.isArray(obj) ? `[${key}]` : `.${key}`));
searchValue(obj[key], value);
path.pop();
}
}
}
// Call the recursive function
searchValue(obj, value);
//If the target value is found, the path string is returned, otherwise an empty string is returned
return result.length > 0 ? result.join('') : '';
}
This is the test example I made:
let obj = {
a:1,
b:"hello",
c:{
a:"target000",
b:"tar",
c:"target_w",
d:[
"target0",
"target1",
"target2",
{
a:2,
b:"target"
}
]
}
}
let res = findValuePath(obj,"target")
console.log(res) // ".c.d[3].b"
console.log(`obj${res}`) // "obj.c.d[3].b"
console.log(eval(`obj${res}`)) // "target"
data.key1.children.key3 === data.key4
would also betrue
, and probably not what you're trying to achieve. – Pryor