0

Is there any best option that i could use to dig, into the deep of objects, beside make some static code like this?

for(let u in menu)
  for(let v in menu.list[u])
    for(let w in menu.list[u].list[v])
      for(let x in menu.list[u].list[v].list[w])
        for(let y in menu.list[u].list[v].list[w].list[x])
          for(let z in menu.list[u].list[v].list[w].lisit[x].list[y])
            console.log(menu.list[u].list[v].list[w].lisit[x].list[y][z])

i couldn find the correct algorithm for this, the object is a bit random, so its probably will be a waste of if the object only have two or even on list element.

the object look like this

 list: {
   somethingA: {
      list: {
        somethingAA: {
          list: {}
        },
        somethingAB: {
          list: {
            somethingABA: {}
            somethingABB: {
               list: {
                 somethingABBA: {}
               }
            }
          }
        }
      }
   },
   somethingB: {
      list: {
        somethingBA: {
          list: {}
        },
        somethingBB: {
          list: {}
        }
      }
   }
 }

i could put break, if the last list element didnt has list element, but how if the list has child list, more than the static loop i made? which i need to be visible.

thanks

Irvan Hilmi
  • 378
  • 1
  • 4
  • 16
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Nick Jun 18 '22 at 08:08
  • https://stackoverflow.com/questions/6969604/recursion-down-dom-tree – iqmaker Jun 18 '22 at 08:16

1 Answers1

2

You could take a recursive approach and iterate only list properties.

const
    visitList = object => {
        if ('list' in object) {
            for (const key in object.list) visitList(object.list[key]);
        } else {
            console.log(object);
        }
    },
    data = { list: { somethingA: { list: { somethingAA: { list: {} }, somethingAB: { list: { somethingABA: {}, somethingABB: { list: { somethingABBA: {} } } } } } }, somethingB: { list: { somethingBA: { list: {} }, somethingBB: { list: {} } } } } };

visitList(data);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392