JavaScript flattening an array of arrays of objects

前端 未结 10 1691
名媛妹妹
名媛妹妹 2020-11-29 06:15

I have an array which contains several arrays, each containing several objects, similar to this.

[[object1, object2],[object1],[object1,object2,object3]]
         


        
10条回答
  •  日久生厌
    2020-11-29 07:07

    You can use Array.concat like bellow:-

    var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
    var flattened = [].concat.apply([],arr);
    

    flattened will be your expected array.

    ES 2020 gives the flat, also flatMap if you want to iterate over, to flat lists of lists:

    [['object1'], ['object2']].flat() // ['object1', 'object2']
    

提交回复
热议问题