如何从键和值中获取javascript对象的路径 [英] How to get the path from javascript object from key and value
本文介绍了如何从键和值中获取javascript对象的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个javascript对象宽度深度.
I have a javascript object width depth.
我需要知道对象ex中此键的确切路径:"obj1.obj2.data1"
I need to know the exact path from this key within the object ex: "obj1.obj2.data1"
我已经知道密钥是data1,值是123.
I already know the key is data1, the value is 123.
我的javascript对象如下
My javascript object look like this
{
obj1: {
obj2: {
data1: 213,
data2: "1231",
obj3: {
data: "milf"
}
}
},
obj4: {
description: "toto"
}
}
我该如何实现?
这是一个jsfiddle: http://jsfiddle.net/3hvav8xf/8/我正在尝试实现getPath.
here is a jsfiddle : http://jsfiddle.net/3hvav8xf/8/ I am trying to implement getPath.
推荐答案
我认为递归函数可以为您提供帮助(更新版本,以检查值)
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));
这篇关于如何从键和值中获取javascript对象的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文