I have an array of objects with this structure:
const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] }
]
It could be deeper but array data would be always json or strings
const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] },
2,
3
]
I would like to get something like this:
const treeDataResult = [
{
label: "0",
value: "0",
children: [
{
label: "0-0",
value: "0-0"
},
{
label: "0-1",
value: "0-1",
}
]
},
{
label: "1",
value: "1",
children: [
{
label: "1-0",
value: "1-0",
},
{
label: "1-1",
value: "1-1",
}
]
},
{
label: "2",
value: "2"
},
{
label: "3",
value: "3"
}
]
My code right now is this:
const treeData = [
{ "0": ["0-0", "0-1"] },
{ "1" : ["1-0", "1-1"] }
];
const convertNode = (parentNode) =>
parentNode.map(
childnode => {
if (typeof(childNode) === 'string')
return {
label: childNode,
value: childNode
}
else
return
childNode.map((key, val) =>
({
label: key,
value: key,
children: convertNode(val)
})
)
}
)
var treeDataResult = convertNode(treeData);
console.log(treeDataResult);