Flatten Javascript array

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

    You can flat the map() result using Array.prototype.flatMap():

    The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

    let list = [
      {
        'items': [
          'item 1',
          'item 2'
        ]
      },
      {
        'items': [
          'item 3'
        ]
      }
    ]
    list = list.flatMap(i => i.items);
    
    console.log(list);

提交回复
热议问题