I need to create a flat array using various hierarchical tree data. I'll get array of tree nodes as string in the form of parentNode-childNode-... This is all dynamic. I tried to convert treeNodeInput into nested object, but couldn't make use of that.
const TREE_DATA = [{
name: 'USA',
children: [{
name: 'Texas',
children: [{
name: 'Dallas'
}, {
name: 'Houston'
}]
}, {
name: 'California',
children: [{
name: 'Los Angeles'
}, {
name: 'San Francisco'
}]
}, {
name: 'New York',
children: [{
name: 'New York City'
}, {
name: 'Buffalo'
}]
}],
}, {
name: 'India',
children: [{
name: 'Bihar',
children: [{
name: 'Patna'
}, {
name: 'Gaya'
}],
}],
}, ];
let treeDataGroupedBy = ['Country', 'State', 'City'];
let treeNodeInput = ['0-0-0', '1-0-1'];
let data = []; /*Expected Result [{
Country: 'USA',
State: 'Texas',
City: 'Dallas'
}, {
Country: 'India',
State: 'Bihar',
City: 'Gaya'
}]*/
for (let item of treeNodeInput) {
let nodesArray = item.split("-");
let count = 0;
let rowObj = {};
for (let node of nodesArray) {
rowObj[treeDataGroupedBy[count]] = Object.keys(TREE_DATA)[Number(node)];
count++;
}
data.push(rowObj);
}
console.log(data)
treeNodeInput = ['0-0-0', '1-0-1'];? Did you define it?tree[1], thentree[1].children[0], thentree[1].children[0].children[1]treeNodeInput.