merry-go-round
merry-go-round

Reputation: 4615

How can I render list items dynamically and recursively from a nested array?

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

Answers (2)

Anthony Gedeon
Anthony Gedeon

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

farvilain
farvilain

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

Related Questions