Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  53] [ 3]  / answers: 1 / hits: 29172  / 13 Years ago, mon, january 9, 2012, 12:00:00

How would you get a JSON path to a given child node of an object?



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:



data.key1.children.key4


Is there any way to get this done in JS?



Thank you in advance.


More From » json

 Answers
6

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?



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



LIVE DEMO



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

[#88137] Sunday, January 8, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cayden

Total Points: 314
Total Questions: 107
Total Answers: 101

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
;