我有一个javascript对象宽度深度。
我需要知道对象ex中此键的确切路径:“ obj1.obj2.data1”
我已经知道键是data1,值是123。
我的javascript对象看起来像这样
{
obj1: {
obj2: {
data1: 213,
data2: "1231",
obj3: {
data: "milf"
}
}
},
obj4: {
description: "toto"
}
}
我该如何实现?
这是一个jsfiddle:http : //jsfiddle.net/3hvav8xf/8/我正在尝试实现getPath。
我认为递归函数可以为您提供帮助(更新版本,以检查值)
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;
};
path({1: 2, s: 5, 2: {3: {2: {s: 1, p: 2}}}}, "s", 1)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句