I am currently working on resolving a problem that involves JSON paths with arrays, and I have devised the following method to tackle it:
function findValuePath(obj, value) {
// Initialize arrays for results and paths
let result = [];
let path = [];
// Recursive function to search for values
function searchValue(obj, value) {
for (let key in obj) {
// Log the path if the current attribute value matches the target value
if (obj[key] === value) {
path.push((Array.isArray(obj) ? `[${key}]` : `.${key}`));
result = path.slice();
path.pop();
}
// Recursively search if the property is an object or array
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);
// Return the path string if the target value is found, otherwise return an empty string
return result.length > 0 ? result.join('') : '';
}
Here is an example test case that I created:
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"