Find all paths of value in a JavaScript object
I found myself with an interesting problem when I was trying to reverse engineer the data structure of an object. I knew the ID was somewhere in this huge object but it was obstruficated. I didn't want to expand every property just to find out where this ID resided.
I came up with this algorithm. It will find all occurrences of a value in an object recursively. It returns an array with all of the paths it found the value in.
const search = (obj, target, path = []) => {
let paths = [];
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
let ref = obj[i];
if (ref === target) {
paths.push([...path, i].join('.'));
}
if (typeof ref === 'object') {
let results = search(ref, target, [...path, i]);
if (results.length > 0) {
paths = paths.concat(results);
}
}
}
}
return paths;
};
Word to the wise, I didn't put cyclical loop detection in this, so don't use it with those kinds of objects. If you do, you are going to have a bad time.
See the JSFiddle for a use case.