JavaScript flattening an array of arrays of objects

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

    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.

    Stay in touch with us:

    ","__v":0},{"_id":"5508e1405c621d4aad2d2969","title":"test english","shortname":"test-page","contents":"

    English Test

    ","__v":0}],[{"_id":"550b336f33a326aaee84f883","shortname":"ok-url","title":"now english","contents":"

    okokko

    ","category":"Transportation","__v":0}]] const result = data.flat(); console.log(result);

提交回复
热议问题