JavaScript flattening an array of arrays of objects

前端 未结 10 1697
名媛妹妹
名媛妹妹 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 06:53

    If you only need simple flatten, this may works:

    var arr = [['object1', 'object2'],['object1'],['object1','object2','object3']];
    var flatenned = arr.reduce(function(a,b){ return a.concat(b) }, []);
    

    For more complex flattening, Lodash has the flatten function, which maybe what you need: https://lodash.com/docs#flatten

    //Syntax: _.flatten(array, [isDeep])
    
    _.flatten([1, [2, 3, [4]]]);
    // → [1, 2, 3, [4]];
    
    // using `isDeep` to recursive flatten
    _.flatten([1, [2, 3, [4]]], true);
    // → [1, 2, 3, 4];
    

提交回复
热议问题