Home > Back-end >  How to iterate over all children elements?
How to iterate over all children elements?

Time:02-18

How to iterate over all children elements?

I have an array that has an infinite number of nested childrens, how do I output all of them?

const data = [
    { title: "Mark", children: [{ title: "Alex" }] },
    {
      title: "Alisa",
      children: [{ title: "Bob", children: [{ title: "Jacob" }] }]
    }
];

I only go through two levels, but there can be as many as you like.

{data.map((item) => {
        return (
          <div>
            {item.title}
            {item.children.map((item) => item.title)}
          </div>
        );
      })}

CodePudding user response:

Make the mapper a named function, and then you'll be able to call it recursively.

const renderItem = item => (
  <div>
    {item.title}
    {item.children?.map(renderItem)}
  </div>
);
return data.map(renderItem);
  • Related