Home>

When there is an array like the one below, repeat ① and ② for allnameI want to output.
① In that hierarchynameToconsole.logOutput with
groupSaykeyIf there is, go down

Currently, it is decided that there are up to 2 levels, so I created it directly, but it seems that it will increase in the future.
I want to concisely modify the code so that it can handle any increase or decrease in the hierarchy.

const arr = [
  {
    name:'taro',
    group: [
      {
        name:'kota',
        group: [
          {
            name:'hiro'
          }
        ]
      },
    ],,
  },
  {
    name:'tatsuya',
    group: [
      {
        name:'shota'
      }
    ]
  }
]

I'm sorry I don't have my own code, but I would appreciate it if you could teach me.

  • Answer # 1

    With a recursive call.

    function foo (a) {
        a.forEach (x =>{
            console.log (x.name);
            if ("group" in x) {
                foo (x.group);
            }
        })
    }
    foo (arr)

  • Answer # 2

    For this proposition, you need to remember the parent of the parent of name
    In terms of processing