JavaScript flattening an array of arrays of objects

前端 未结 10 1679
名媛妹妹
名媛妹妹 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:13

    I've noticed that people are using recursions which are not cost friendly, especially with new ES6 standards giving us the power of spread operators. When you're pushing the items into the master array just use ... and it will automatically add flattened objects. Something like

    array.push(...subarray1)    // subarray1 = [object1, object2]
    array.push(...subarray2)    // subarray2 = [object3]
    array.push(...subarray3)    // subarray3 = [object4,object5, object6]
    // output -> array = [object1, object2, object3, object4, object5, object6]
    

提交回复
热议问题