1

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?

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

How do I build <li> with it? If we can avoid preprocessing and render it dynamically, that will be great
Well maybe you should participate at least a little bit in your own work don't you think? I solved the 'hard' part, the recursion. Now the rest is up to you. :)
1

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.