JavaScript flattening an array of arrays of objects

前端 未结 10 1603
名媛妹妹
名媛妹妹 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];
    
    0 讨论(0)
  • 2020-11-29 07:01

    A recursive solution for deep (nested) flattening:

    function flatten(a) {
      return Array.isArray(a) ? [].concat.apply([], a.map(flatten)) : a;
    }
    

    A bit more compactly with ES6:

    var flatten = a => Array.isArray(a) ? [].concat(...a.map(flatten)) : a;
    

    For fun, using a generator named F for "flatten", to lazily generate flattened values:

    function *F(a) {
      if (Array.isArray(a)) for (var e of a) yield *F(e); else yield a;
    }
    
    >> console.log(Array.from(F([1, [2], 3])));
    << [ 1, 2, 3 ]
    

    For those not familiar with generators the yield * syntax yields values from another generator. Array.from takes an iterator (such as results from invoking the generator function) and turns it into an array.

    0 讨论(0)
  • 2020-11-29 07:01
    var arr = [1,[9,22],[[3]]];
    var res = [];
    
    function flatten(arr){
    for(let i=0;i<arr.length;i++){
    if(typeof arr[i] == "number"){
    res.push(arr[i]);
    }
    else if(typeof arr[i] == "object"){
    fatten(arr[i]);
    }
    }
    }
    

    Calling function

    flatten(arr);
    console.log(res);
    

    Result  

    [1, 9, 22, 3]
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
  • 2020-11-29 07:08

    you can use flat() :

    const data = [ [{id:1}, {id:2}], [{id:3}] ];
    const result = data.flat();
    console.log(result);
    
    // you can specify the depth
    
    const data2 = [ [ [ {id:1} ], {id:2}], [{id:3}] ];
    const result2 = data2.flat(2);
    
    console.log(result2);

    in your case :

    const data = [[{"_id":"55064111d06b96d974937a6f","title":"Generic Title","shortname":"generic-title","contents":"<p>The Healing Center offers practical, social, and spiritual support to individuals and families. Services include, but are not limited to: food and clothing, job skills training and job search assistance, auto repair (Saturdays only), mentoring, financial counseling, tutoring, prayer, life skills training, and helpful information about local community services.</p><p>Stay in touch with us:</p>","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"<h2>English Test</h2>","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"<p>okokko</p>","category":"Transportation","__v":0}]]
    
    const result = data.flat();
    
    console.log(result);

    0 讨论(0)
  • 2020-11-29 07:09

    Recursively flatten an array:

    function flatten(array) {
       return !Array.isArray(array) ? array : [].concat.apply([], array.map(flatten));
    }
     
    var yourFlattenedArray = flatten([[{"_id":"55064111d06b96d974937a6f","title":"Generic Title","shortname":"generic-title","contents":"<p>The Healing Center offers practical, social, and spiritual support to individuals and families. Services include, but are not limited to: food and clothing, job skills training and job search assistance, auto repair (Saturdays only), mentoring, financial counseling, tutoring, prayer, life skills training, and helpful information about local community services.</p><p>Stay in touch with us:</p>","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"<h2>English Test</h2>","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"<p>okokko</p>","category":"Transportation","__v":0}]]
    );
    
    log(yourFlattenedArray);
    
    function log(data) {
      document.write('<pre>' + JSON.stringify(data, null, 2) + '</pre><hr>');
    }
    * {font-size: 12px; }

    0 讨论(0)
提交回复
热议问题