이 내가이 작업을 수행 한 방법입니다 작동 할 수 있습니다. 테스트를 위해
/**
* 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, '.$1'); // 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;
}
, 사람을 도움이 될 것입니다
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
희망.
검색 변수가 문자열 개체를 가리키는 경우 (예에서와 같이) 'data.key1.children.key3 === data.key4'처럼 해당 경로를 안정적으로 검색 할 수 없습니다. 또한 '사실'일 것이고, 아마도 당신이 성취하고자하는 것이 아닙니다. – Yoshi
감사합니다. Yoshi, 코드 샘플을 업데이트했습니다. 이제 참조가 다른 객체를 가리키고 있습니다. – user1138959