javascriptconcatenationreduceflatmapflat

Obtain values fron nested array of objects


I have the fallowing data structure:

products = [
    {
        name: 'Menu1',
            subitems: [
                {
                    name: 'Menu2'
                },
        ]
    },
    {
        name: 'Menu3',
            subitems: [
                {
                    name: 'Menu4',
                    subitems: [
                        {
                            name:'Menu5'
                        },
                        {
                            name:'Menu6'
                        }
                    ]
                },
        ]
    },
]

Want to obtain all the names values inside of it, no matter how deep nested it is. I 've tried solutions related to flat, reduce, concat, map, for of, etc but I never get the deepest level 'Menu5' and 'Menu6'

I think this is saying recursivity out loud but I can't implement it


Solution

  • Using Array#reduce:

    const _getNames = (products = []) =>
      products.reduce((names, { name, subitems = [] }) => {
        names.push(name);
        if(subitems.length > 0) {
          names.push(..._getNames(subitems));
        }
        return names;
      }, []);
    
    const products = [
      { 
        name: 'Menu1',
        subitems: [ 
          { name: 'Menu2' } 
        ] 
      },
      { 
        name: 'Menu3', 
        subitems: [ 
          { name: 'Menu4', 
            subitems: [ 
              { name:'Menu5' }, { name:'Menu6' } 
            ] 
          }
        ]
      }
    ];
    console.log( _getNames(products) );