Skip to content
Advertisement

Need to loop till the array inside the array has value

I need to loop(map) the array till inside array have value. If inside array is empty need to stop the loop

var parent = {
  children: [
    {
      id: '1',
      title: 'test1',
      children: [
        {
          id: '2',
          title: 'test 21',
          children: [
            {
              id: '3',
              title: 'test3',
              children: [
                {
                  id: '4',
                  title: 'test5',
                  children: []
                }
              ]
            }
          ]
        }
      ]
    }
  ]
};

Loop the array till inside the children array has value.

Advertisement

Answer

You can recursively loop through the children array and push the title to another array. Then can loop through this new array to render titles.

export default function App() {
  const titleArray = []

  const recursive = (children) => {
    children.map((newChild) => {
      newChild.title && titleArray.push(newChild.title)
      if(newChild.children) {
        recursive(newChild.children)
      }
    })
  }
  recursive(parent.children)
  return (
    <div className="App">
      {titleArray.map((title, index) => (
         <div key={index}>{title}</div>
      ))}
    </div>
  );
}

Sandbox URL: https://codesandbox.io/s/naughty-archimedes-0hzy2?file=/src/App.js:668-1111

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement