Flatten Javascript array

前端 未结 5 1343
悲&欢浪女
悲&欢浪女 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:14

    You could use reduce(). There is no way to avoid looping since Array prototype methods do loops internally

    let list = [
      {
        'items': [
          'item 1',
          'item 2'
        ]
      },
      {
        'items': [
          'item 3'
        ]
      }
    ];
    
    const res = list.reduce((a,c) => [...a, ...c.items],[])
    
    console.log(res)

提交回复
热议问题