0

I have the following javascript array of objects main array is root have children

Array(2) [ 
    { id: "3", children: [] }, 
    { id: "8", children: [{ id: "476", children: [] }] } 
]

I want to print all with loop

I try this code

    let idx= [];
       for(var i = 0; i < root.length; i++){
                idx[i]=root[i].id;

        }
            console.log(idx);

this code print root ids but I want all root and children ids

khalid seleem
  • 117
  • 1
  • 8

1 Answers1

0

Recursivly iterate over the array:

function get_id(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i].id);
    if (arr[i].children[0]) { 
      // if got at least one child, iterate over children array.
      get_id(arr[i].children);
    }
  }
}

let test_arr = [
  {
    id: "3",
    children: [
      {
        id: "333",
        children: [
          { id: "999", children: [] },
          { id: "321", children: [] },
        ],
      },
    ],
  },

  { id: "8", children: [{ id: "476", children: [] }] },
];

get_id(test_arr);
Rani Giterman
  • 708
  • 2
  • 6
  • 17