Javascript/JSON 获取给定子节点的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8790607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/JSON get path to given subnode?
提问by user1138959
How would you get a JSON path to a given child node of an object?
您将如何获得对象的给定子节点的 JSON 路径?
E.g.:
例如:
var data = {
key1: {
children: {
key2:'value',
key3:'value',
key4: { ... }
},
key5: 'value'
}
An variable with a reference to key4 is given. Now I'm looking for the absolute path:
给出了一个引用 key4 的变量。现在我正在寻找绝对路径:
data.key1.children.key4
Is there any way to get this done in JS?
有没有办法在 JS 中完成这项工作?
Thank you in advance.
先感谢您。
采纳答案by Adam Rackis
So you have a variable with the value "key3", and you want to know how to access this property dynamically, based on the value of this string?
所以你有一个值为“key3”的变量,你想知道如何根据这个字符串的值动态访问这个属性?
var str = "key3";
data["key1"]["children"][str];
EDIT
编辑
Wow, I can't believe I got this on the first try. There might be some bugs in it, but it works for your test case
哇,我简直不敢相信我第一次尝试就得到了这个。它可能存在一些错误,但它适用于您的测试用例
var x = data.key1.children.key4;
var path = "data";
function search(path, obj, target) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
if (obj[k] === target)
return path + "['" + k + "']"
else if (typeof obj[k] === "object") {
var result = search(path + "['" + k + "']", obj[k], target);
if (result)
return result;
}
}
return false;
}
var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']
回答by George Siggouroglou
This is the way i have done this.
这是我这样做的方式。
/**
* Converts a string path to a value that is existing in a json object.
*
* @param {Object} jsonData Json data to use for searching the value.
* @param {Object} path the path to use to find the value.
* @returns {valueOfThePath|undefined}
*/
function jsonPathToValue(jsonData, path) {
if (!(jsonData instanceof Object) || typeof (path) === "undefined") {
throw "Not valid argument:jsonData:" + jsonData + ", path:" + path;
}
path = path.replace(/\[(\w+)\]/g, '.'); // convert indexes to properties
path = path.replace(/^\./, ''); // strip a leading dot
var pathArray = path.split('.');
for (var i = 0, n = pathArray.length; i < n; ++i) {
var key = pathArray[i];
if (key in jsonData) {
if (jsonData[key] !== null) {
jsonData = jsonData[key];
} else {
return null;
}
} else {
return key;
}
}
return jsonData;
}
For testing,
供测试用,
var obj = {d1:{d2:"a",d3:{d4:"b",d5:{d6:"c"}}}};
jsonPathToValue(obj, "d1.d2"); // a
jsonPathToValue(obj, "d1.d3"); // {d4: "b", d5: Object}
jsonPathToValue(obj, "d1.d3.d4"); // b
jsonPathToValue(obj, "d1.d3.d5"); // {d6: "c"}
jsonPathToValue(obj, "d1.d3.d5.d6"); // c
Hope that will help someone.
希望这会帮助某人。