1

I have a javascript object with nested objects like this:

Object { 
    Id: 1,
    Descendants: [{
      Object {
         id:2
         Descendants:[
           {Object
             {id:3
              Descendants[]
}}]}]

Now I want to iterate through all of the descendant properties and print them. What would be the cleanest way to do this? Thanks a lot in advance!

CuriousCat
  • 11
  • 1
  • Does this answer your question? [looping through an object (tree) recursively](https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively) – Ivar Sep 05 '22 at 09:35
  • Does this answer your question? [Traverse all the Nodes of a JSON Object Tree with JavaScript](https://stackoverflow.com/questions/722668/traverse-all-the-nodes-of-a-json-object-tree-with-javascript) – imjared Sep 05 '22 at 14:28

1 Answers1

0

You could try this:

const o = {
  id: 1,
  Descendants: [
    {
      id: 2,
      Descendants: [
        {
          id: 3,
          Descendants: [],
        },
      ],
    },
  ],
}

function doSomething(o) {
  // Write Do whatever you want to do with the objects
  console.log(o.id)

  // And to the recursively
  for (const child of o.Descendants) {
    doSomething(child)
  }
}

doSomething(o)
some-user
  • 3,888
  • 5
  • 19
  • 43