I appreciate all the feedback on my first question. I will give it another shot.
Here is a JSON object example:
var obj = {
"data":[
{
"data":{
"title":"title1",
"attr":{
"id":111
}
},
"children":[
{
"data":{
"title":"title2",
"attr":{
"id":222
}
},
"children":[
{
"data":{
"title":"title3",
"attr":{
"id":333
}
}
}
]
},
{
"data":{
"title":"title4",
"attr":{
"id":444
}
},
"children":[
{
"data":{
"title":"title5",
"attr":{
"id":555
}
}
}
]
}
]
}
]
};
I am seeking assistance in tracing a "lineage" to a specific id value through the title properties. For example, if given 222, the expected result is title 1; for id 333, title1 > title 2; and for id 555, title1 > title 4. Note that these are siblings of parents rather than direct parents.
This is what I have attempted so far:
var x = 555;
var path = "";
function search(path, obj, target) {
for (var k in obj) {
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, obj, x);
console.log(path); // "['data']['0']['children']['1']['children']['0']['data']['attr']['id']"
However, I have been unable to retrieve the title attributes. Any help would be appreciated. Thank you for your patience!