I've been working on creating a recursive function with some guidance I received here: looping through an object (tree) recursively
The goal is to traverse the object 'o' and generate a new one where each key is associated with its parents in the hierarchy.
Personally, recursion isn't my strong suit, so maybe you can give it a shot :-) ... if you're up for experimenting with actual data, you can find it here
function eachRecursive(obj) {
for (var k in obj) {
if (typeof obj[k] == "object" && obj[k] !== null ) {
eachRecursive(obj[k])
}
else {
// perform action to add to codes
}
}
}
var o = {
"1": {
name: "hi 1",
children: {
"1.1": {
name: "hi 1.1",
children: {
"1.1.1": {
name: "hi 1.1.1",
children: {}
}
}
},
"1.2": {
name: "hi 1.2",
children: {}
}
}
},
"2": {
name: "hi 2",
children: {
"2.1": {
name: "hi 2.1",
children: {}
}
}
}
}
var codes = {}
eachRecursive(o)
console.log(codes)
// Desired output.
//{
// "1": {
// "name":"hi 1",
// "parents":[]
// },
// "2": {
// "name": "hi 2",
// "parents": []
// },
// "1.1": {
// "name": "hi 1.1",
// "parents": ["1"]
// },
// "1.1.1": {
// "name": "hi 1.1.1",
// "parents": ["1", "1.1"]
// },
// "1.2": {
// "name": "hi 1.2",
// "parents": ["1"]
// },
// "2.1": {
// "name": "hi 2.1",
// "parents": ["2"]
// }
//}