Skip to content
Advertisement

Iterate through all children and children children of an object

I have an object with children objects, and even great grandchildren objects.

I am currently using

JavaScript

Which produces, for example:

  • created_at: 2021-01-01T00:00:00.000Z
  • id: string
  • data: [object Object]
  • items: [object Object],[object Object]

How do I iterate through any number of child objects to return something similar to

  • created_at: 2021-01-01T00:00:00.000Z
  • id: string
  • data: [object Object]
  • data: 1 of 1 {contents}
  • items: 1 of 2 {contents}
  • items: 2 of 2 {contents}

The “1 of 2” isn’t needed, but demonstrates my output goal.

Advertisement

Answer

This is a situation where recursion is useful. For example:

JavaScript

Live example:

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