bft/bfs/dft/dfs on nested object
function getPath(obj, value) {
if (obj.constructor !== Object) {
throw new TypeError('getPath() can only operate on object with Object as constructor');
}
var path = [];
var found = false;
function search(haystack) {
for (var key in haystack) {
path.push(key);
if (haystack[key] === value) {
found = true;
break;
}
if (haystack[key].constructor === Object) {
search(haystack[key]);
if (found) break;
}
path.pop();
}
}
search(obj);
return path;
/*
Or alternately if you want to keep mixed return
return found ? path : false;
*/
}
var nestedObj = {
"rrr": {
"ddd": {
"aa bbbb": {
1: 30009463
},
"cc dddd.": {
1: 30010338
},
"e fff": {
1: 30007744
},
"d-Pool": {
1: 30018363,
2: 30017133,
3: 30013107
},
"e e g": {
1: 30011707,
2: 30017137
},
"f f.-f. (f)": {
1: 30012329
},
"g": {
1: 30011894
}
}
}
};
console.log(getPath(nestedObj, 30017137));
console.log(getPath(nestedObj, 'no value'));