JavaScript flattening an array of arrays of objects

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

    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}]] ); log(yourFlattenedArray); function log(data) { document.write('
    ' + JSON.stringify(data, null, 2) + '

    '); }
    * {font-size: 12px; }

提交回复
热议问题