Reputation: 4615
Given the output, I want to list <li>
dynamically
results = [
{
name: 'a1',
results: []
},
{
name: 'a2',
results: [
{
name: 'b1',
results: []
},
{
name: 'b2',
results: [
{
name: 'c1',
}
]
}
]
},
{
name: 'a3',
}
]
This is expected output
<li>a1</li>
<li>a2</li>
<li>b1</li>
<li>b2</li>
<li>c1</li>
<li>a3</li>
My pseudo-code but I think this is not even close... I think I need "recursive" solution to tackle this problem
input.map((r) => {
if(r) {
return renderResult(r);
} <<< This is not a recursive way...
return renderResult(r.results.?);
});
How do I list this dynamically and recursively?
Upvotes: 1
Views: 207
Reputation: 383
Here's my take on the problem!
For dynamically inserting the li tags into the dom, use createElement and append!
const results = [
{
name: 'a1',
results: []
},
{
name: 'a2',
results: [
{
name: 'b1',
results: []
},
{
name: 'b2',
results: [
{
name: 'c1',
}
]
}
]
},
{
name: 'a3',
}
]
const getNames = (list) => {
const names = [];
function getDeepNames(list) {
for (let obj of list) {
names.push(obj.name);
if (Array.isArray(obj.results)) {
getDeepNames(obj.results);
}
}
return names;
}
return getDeepNames(list)
}
console.log(getNames(results))
Upvotes: 1
Reputation: 2562
Your solution is nearly this one
function generate(arr) {
const items = [];
arr.forEach( i => {
items.push(i.name); //Or whatever you want
});
return items;
}
Just introduce recursivity
function generate(arr) {
const items = [];
arr.forEach( i => {
items.push(i.name);
if( !!i.results ){
const subs = generate(i.results);
subs.forEach( s => items.push(s));
}
});
return items;
}
Upvotes: 1