Here's a recursive function I made, that searches through the object and return the path as a.b.c
var obj = {
"a": {
"b": {
"c": {
1: 6
}
}
},
"d": {
"e": 7
},
"h": {
"g": 7
},
"arr": {
"t": [22, 23, 24, 6]
}
};
This will return the first path that is matched as a string.
var getObjectPath = function(search, obj) {
var res = false;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] == "object") { //If value is an object, call getObjectPath again!
if (res = getObjectPath(search, obj[key])) {
res = key + "." + res;
return res;
}
} else if (search === obj[key]) {
return key; //Value found!
}
}
}
return res;
}
console.log(getObjectPath(7, obj)); //d.e
console.log(getObjectPath(6, obj)); //a.b.c.1
console.log(getObjectPath(24, obj)); //arr.t.2 //2 is the index
Multiple matches search, will return an array of paths
var getObjectPathMultiple = function(search, obj, recursion) {
var res = false;
var paths = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] == "object") {
if (res = getObjectPathMultiple(search, obj[key], true)) {
res = key + "." + res;
if (!recursion)
paths.push(res);
else return res;
}
} else if (search === obj[key]) {
return key;
}
}
}
return recursion ? res : paths;
}
console.log(getObjectPathMultiple(7, obj)); //["d.e", "h.g"]
console.log(getObjectPathMultiple(6, obj)); //["a.b.c.1", "arr.t.3"]
console.log(getObjectPathMultiple(24, obj)); //["arr.t.2"]