I want to get the output as:
options: [{
id: 'parent1',
label: 'parent1',
children: [{
id: 'child1',
label: 'child1',
children: [{
id: 'lastChild1',
label: 'lastChild1',
}]
}, {
id: 'child2',
label: 'child2',
children: [{
id: 'lastChild2',
label: 'lastChild2',
}]
}]
}]
However, the output from getOptions()
is in the format where the children property array of parent1
object contain only the second child in the above format, first child is kind of overwritten or not visited by the for..in
loop in the recurseList()
.
Can anyone fix the code to output the first child child1
along with child2
as well, basically any level of nesting.
var myObj = {
parent1: {
child1: {
lastChild1: { test: 'cool'}
},
child2: {
lastChild2: { test: 'cool'}
}
},
parent2: {
child2_1: {
lastChild2_1: { test: 'cool'}
},
child2_2: {
lastChild2_2: { test: 'cool'}
}
}
}
var result = getOptions(myObj)
console.log('result', result)
function getOptions(obj) {
var options = []
for (key in obj) {
var data = recurseList(obj[key])
options.push(data)
}
return options
}
function recurseList(obj) {
let data= {}
let option= []
for (key in obj) {
data.id = key
data.label = key
data.children = []
if(obj[key] instanceof Object) {
var val = recurseList(obj[key])
data.children.push(val)
}
}
return data
}
Actually, I want data from my firebase real-time-database as show in the image below:
to be in the format for this vuejs plugin: https://vue-treeselect.js.org
Thanks
parent2
orlastchild1
andtest
? Is it only because the value of the former ones are objects and the latter is a string? Or is there something else going on with property names or some such?{id: 'lastChild1', label: 'lastChild1'}
in your sample output above not includechildren: {id: 'test', label: 'test'}
? What distinguishes the nodetest
from any of its ancestor nodes?