How To Get The Path From Javascript Object From Key And Value
Solution 1:
I think recursive function can help to you (Updated version, to check value)
functionpath(c, name, v, currentPath, t){
var currentPath = currentPath || "root";
for(var i in c){
if(i == name && c[i] == v){
t = currentPath;
}
elseif(typeof c[i] == "object"){
returnpath(c[i], name, v, currentPath + "." + i);
}
}
return t + "." + name;
};
console.log(path({1: 2, s: 5, 2: {3: {2: {s: 1, p: 2}}}}, "s", 1));
Solution 2:
The following finds the path in any level of nested objects. Also with arrays. It returns all the paths found, which is something you want if you have keys with the same name.
I like this approach because it works with lodash
methods get
and set
out-of-the-box.
functionfindPathsToKey(options) {
let results = [];
(functionfindKey({
key,
obj,
pathToKey,
}) {
const oldPath = `${pathToKey ? pathToKey + "." : ""}`;
if (obj.hasOwnProperty(key)) {
results.push(`${oldPath}${key}`);
return;
}
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
if (Array.isArray(obj[k])) {
for (let j = 0; j < obj[k].length; j++) {
findKey({
obj: obj[k][j],
key,
pathToKey: `${oldPath}${k}[${j}]`,
});
}
}
if (obj[k] !== null && typeof obj[k] === "object") {
findKey({
obj: obj[k],
key,
pathToKey: `${oldPath}${k}`,
});
}
}
}
}
})(options);
return results;
}
findPathsToKey({ obj: objWithDuplicates, key: "d" })
// ["parentKey.arr[0].c.d", "parentKey.arr[1].c.d", "parentKey.arr[2].c.d"]
Try it here - https://jsfiddle.net/spuhb8v7/1/
If you want the result to be a single key (first encountered), you can change the results
to be a string and if defined, then return the function with it.
Solution 3:
I ended up with the following function, that works with nested objects/arrays :
functionfindPath (obj, name, val, currentPath) {
currentPath = currentPath || ''let matchingPath
if (!obj || typeof obj !== 'object') returnif (obj[name] === val) return`${currentPath}['${name}']`for (const key ofObject.keys(obj)) {
if (key === name && obj[key] === val) {
matchingPath = currentPath
} else {
matchingPath = findPath(obj[key], name, val, `${currentPath}['${key}']`)
}
if (matchingPath) break
}
return matchingPath
}
const treeData = [{
id: 1,
children: [{
id: 2
}]
}, {
id: 3,
children: [{
id: 4,
children: [{
id: 5
}]
}]
}]
console.log(findPath (treeData, 'id', 5))
Solution 4:
JSON Object can be handled in JavaScript as associative array.
So You can cycle through and store indexes of "parents" in some variables.
Assume the whole object to be stored in variable called obj.
for( var p1 in obj )
{
for( var p2 in obj[ p1 ] ) { for( var p3 in obj[ p1 ][ p2 ] ) { // obj[ p1 ][ p2 ][ p3 ] is current node // so for Your example it is obj.obj1.obj2.data1 } }
}
Hope answer was helpful.
Solution 5:
I would do this job as follows;
Object.prototype.paths = function(root = [], result = {}) {
var ok = Object.keys(this);
return ok.reduce((res,key) => { var path = root.concat(key);
typeofthis[key] === "object" &&
this[key] !== null ? this[key].paths(path,res)
: res[this[key]] == 0 || res[this[key]] ? res[this[key]].push(path)
: res[this[key]] = [path];
return res;
},result);
};
var myObj = {
obj1: {
obj2: {
data1: 213,
data2: "1231",
obj3: {
data: "milf"
}
}
},
obj4: {
description: "toto",
cougars: "Jodi",
category: "milf"
}
},
value = "milf",
milfPath = myObj.paths()[value]; // the value can be set dynamically and if exists it's path will be listed.console.log(milfPath);
A few words of warning: We should be cautious when playing with the Object prototype. Our modification should have the descriptor enumerable = false
or it will list in the for in
loops and for instance jQuery will not work. (this is how silly jQuery is, since apparently they are not making a hasOwnProperty
check in their for in loops) Some good reads are here and here So we have to add this Object method with Object.defineProperty()
to make it enumerable = false;
. But for the sake of simplicity and to stay in the scope of the question i haven't included that part in the code.
Post a Comment for "How To Get The Path From Javascript Object From Key And Value"