I'm currently working on converting two lists into JSON format.
Let's take a look at an example:
list1 = ['a','b','a']
list2 = ['q','r','s']
The conversion should result in:
[{
"name": "g",
"children": [{
"name": "a",
"children": [{
"name": "q"
}, {
"name": "s"
}]
},
{
"name": "b",
"children": [{
"name": "r"
}]
}
]
}]
I have come close with the following code:
list1 = ['a','b','a']
list2 = ['q','r','s']
nameDict = {}
childrenDict = {}
list1 = list1.map(x => {
return({name: x});
});
console.log(list1);
list2 = list2.map(x => {
return({children: x});
});
console.log(list2);
var combined = list1.map(function(e, i) {
return [e, list2[i]];
});
console.log(JSON.stringify(combined))
However, the output is currently:
[[{"name":"a"},{"children":"q"}],
[{"name":"b"},{"children":"r"}],
[{"name":"a"},{"children":"s"}]]
Any suggestions on how to combine these elements into the desired format?
[{
"name": "g",
"children": [{
"name": "a",
"children": [{
"name": "q"
}, {
"name": "s"
}]
},
{
"name": "b",
"children": [{
"name": "r"
}]
}
]
}]