[英]How to get the path leading to given key / value in JavaScript object?
I looked around but didn't find a solution for this problem : 我环顾四周,但没有找到解决此问题的方法:
I'm trying to get the full path (list of keys) leading to given key or value (taking into accounts dupes) . 我试图获取导致给定键或值(考虑重复)的完整路径(键列表)。
I know its similar to this question : how to get the path of an object's value from a value in javascript 我知道它类似于这个问题: 如何从javascript中的值获取对象值的路径
But different in the way that you may find : 但是您可能会发现不同的方式:
- by key -按键
- by value -按价值
- if any dupes are present, it should return an array of all possibilities -如果存在任何欺骗,则应返回所有可能性的数组
An short example being more speaking than a long speech : 一个简短的例子胜于雄辩:
Sample code : 样例代码:
var data = {
"key1": {
"key1SubKey1": {
"key1SubSubKey1": "key1SubSubKey1_value"
},
"key1SubKey2": {
"key1SubSubKey2": "key1SubSubKey2_value"
},
"key1SubKey3": {
"key1SubSubKey3": "key1SubSubKey3_value"
},
"duplicatedKey": "duplicated_value"
},
"key2": {
"key2SubKey1": {
"key2SubSubKey1": "key2SubSubKey1_value"
},
"key2SubKey2": {
"key2SubSubKey2": "key2SubSubKey2_value"
},
"key2SubKey3": {
"key2SubSubKey3": "key2SubSubKey3_value"
},
"duplicatedKey": "duplicated_value"
}
}
Usage example 使用范例
Search by value 按价值搜索
getPathFromValue (data, "key2SubSubKey1_value") ;
// This should return : data['key2']['key2SubKey1']['key2SubSubKey1']
getPathFromValue (data, "duplicated_value") ;
// [ data['key1']['duplicatedKey'], data['key2']['duplicatedKey'] ]
Search by key 按键搜索
getPathFromKey (data, "key2SubSubKey1") ;
// data['key2']['key2SubKey1']
getPathFromKey (data, "duplicatedKey") ;
// [ data['key1'], data['key2'] ]
please try the following: 请尝试以下操作:
function findValue(data, value,path){
if(typeof(data) != "object" || Object.keys(data).length == 0)
return { "path" : "" , "value" : ""};
for(var prop in data) {
if (data[prop] == value)
return { "path" : path + "['" + prop + "']" , "value" : value};
}
for(var prop in data) {
var result = findValue(data[prop],value,path === undefined ? "['" + prop + "']" : path + "['" + prop + "']" );
if (typeof(result) !== typeof(undefined) && result.value != "") {
return result;
}
}
}
execution of var result = findValue(data,"key1SubSubKey1_value") will result with an object with properties: value and path. var result = findValue(data,“ key1SubSubKey1_value”)的执行将产生具有以下属性的对象:值和路径。
to get the path just access result.path. 要获取路径,只需访问result.path。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.