Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
74
rated 0 times [  77] [ 3]  / answers: 1 / hits: 25655  / 10 Years ago, wed, august 20, 2014, 12:00:00

I have a javascript object width depth.



I need to know the exact path from this key within the object ex: obj1.obj2.data1



I already know the key is data1, the value is 123.



My javascript object look like this



{
obj1: {
obj2: {
data1: 213,
data2: 1231,
obj3: {
data: milf
}
}
},
obj4: {
description: toto
}
}


How could I achieve that ?



here is a jsfiddle : http://jsfiddle.net/3hvav8xf/8/
I am trying to implement getPath.


More From » object

 Answers
14

I think recursive function can help to you (Updated version, to check value)




function path(c, name, v, currentPath, t){
var currentPath = currentPath || root;

for(var i in c){
if(i == name && c[i] == v){
t = currentPath;
}
else if(typeof c[i] == object){
return path(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));




[#69715] Monday, August 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiasavannahw

Total Points: 448
Total Questions: 122
Total Answers: 113

Location: Maldives
Member since Tue, Dec 21, 2021
3 Years ago
;