Here is my nested object and I need to add “name”, “children” for all parent nodes, and “name”, “value” for last nodes:
{
"myObj": {
"a": {
"b": {
"testB1": "10",
"testB2": "20",
},
"c": {
"testC1": "43",
"testC2": "",
"testC3": [
{
"aa": "34",
},
{
"bb": "43",
"cc": ""
},
],
"testC4": {
"ee": {
"eee1": "11",
"eee2": [
{
"f": "50",
},
{
"i": "70",
}
],
"eee3": "1"
},
"ee": "1"
}
}
}
}
}
Here is what I need (all names and the depth are random):
{
"name": "myObj", children: [{
"name": "a", children: [{
"name": "b", children:[{
"name": "testB1", value: "10",
"name": "testB2": value: "20",
}],
"name": "c", children: [{
"name": "testC1": value: "43",
"name": "testC2": value: "",
"name": "testC3", children: [
{
"name": "aa", value: "34",
},
{
"name": "bb", value: "43",
"name": "cc", value: ""
},
],
"name": "testC4", children: [{
"name": "ee", children: [{
"name": "eee1", value: "11",
"name": "eee2", children: [
{
"name": "f", value: "50",
},
{
"name": "i", value: "70",
}
],
"name": "eee3", value: "1"
}],
"name": "ee", value: "1"
}]
}]
}]
}]
}
Here is my recursive function:
function visitDescendants(obj, callback) {
for (const [key, value] of Object.entries(obj)) {
if (value && typeof value === "object") {
let newObj = Object.entries(obj).map( ([key,value]) => ({name: key, children: [value]}) );
// Recurse
visitDescendants(value, callback);
} else {
let newObj = Object.entries(obj).map( ([key,value]) => ({name: key, value: value}) );
callback(key, value);
}
}
}
I can iterate through my object, I can build my desire node, I print out all key values at the last level, but I cannot build the whole object:
visitDescendants(obj, (key, value) => {
console.log(`${key}: ${value}`);
});