Javascript / JSON obtient-il un chemin vers un sous-nœud donné?

Comment obtiendriez-vous un chemin JSON vers un nœud enfant donné d'un objet?

Par exemple:

var data = { key1: { children: { key2:'value', key3:'value', key4: { ... } }, key5: 'value' } 

Une variable avec une référence à la clé4 est donnée. Maintenant, je cherche le chemin absolu:

 data.key1.children.key4 

Y a-t-il un moyen de faire cela dans JS?

Merci d'avance.

Donc, vous avez une variable avec la valeur "key3", et vous voulez savoir comment accéder à cette propriété dynamiquement, en fonction de la valeur de cette chaîne?

 var str = "key3"; data["key1"]["children"][str]; 

MODIFIER

Wow, je ne peux pas croire que j'ai eu ça sur le premier essai. Il pourrait y avoir des bugs, mais cela fonctionne pour votre cas de test

DEMO EN DIRECT

 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'] 

C'est comme ça que j'ai fait cela.

 /** * 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; } 

Pour tester,

 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 

J'espère que cela aidera quelqu'un.