const obj = {
    id: 1,
    name: "Parent",
    children: [
      {
        id: 2,
        name: "Child 1",
        children: [
          {
            id: 5,
            name: "Grandchild 1.1",
            children: [],
          },
          {
            id: 6,
            name: "Grandchild 1.2",
            children: [],
          },
        ],
      },
      {
        id: 3,
        name: "Child 2",
        children: [],
      },
      {
        id: 4,
        name: "Child 3",
        children: [
          {
            id: 7,
            name: "Grandchild 3.1",
            children: [
              {
                id: 10,
                name: "Grandchild 3.1",
                children: [
                  {
                    id: 11,
                    name: "Grandchild 3.1",
                    children: [{
                    id: 15,
                    name: "Grandchild 789.1",
                    children: [],
                  },
],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  };
  
 
      

  
const collectNames = (obj) => {
    let arr = []
    arr.push(obj.name)
    if(obj?.children?.length){
        obj.children.map((item)=>{
            arr = [...arr, ...collectNames(item)]
        })
    }
    return arr
}

console.log(collectNames(obj))


























Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: