Flatten Javascript array

前端 未结 5 1231
悲&欢浪女
悲&欢浪女 2021-01-29 12:36

I have an array of objects like this:

let list = [
  {
    \'items\': [
      \'item 1\',
      \'item 2\'
    ]
  },
  {
    \'items\': [
      \'item 3\'
    ]         


        
5条回答
  •  盖世英雄少女心
    2021-01-29 13:16

    you can use the Array.reduce method and follow the docs here

    {
        let list = [
          {
            'items': [
              'item 1',
              'item 2'
            ]
          },
          {
            'items': [
              'item 3'
            ]
          }
        ];
    
        /**
        * @parameter {Array} arg
        */
        function splat (arg) {
            return arg.reduce((total, { items }) => [...total, ...items], []);
        }
    
        console.log(splat(list));
    }
    

    You could also play with recursive function to make a more generic function that accepts array of nested objects.

提交回复
热议问题