简体   繁体   中英

Merge arrays inside an array in javascript

Going through the link Merge/flatten an array of arrays in JavaScript? is somewhat what i need. But with that link and many other links shows merging of arrays of two arrays. What I have is as follows

[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         }
      ]
   },
   {
      "setter":[
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]

That is I have an array and inside that array I have an array "setter". What I want is actually merging all setter array as a single array. Having said the merge should produce below output

[
   {
      "setter":[
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":1
         },
         {
            "joinedcond":"and"
         },
         {
            "keyname":"Sample Size",
            "cond":"=",
            "value":2
         }
      ]
   }
]

Help would be appreciated. Thanks

You can do it by using Array#reduce

 var arr = [{"setter":[{"keyname":"Sample Size","cond":"=","value":1}]},{"setter":[{"joinedcond":"and"},{"keyname":"Sample Size","cond":"=","value":2}]}]; var finalArr = arr.reduce((a,x)=>{ (a[0].setter = a[0].setter || []).push(...x.setter); return a; },[{}]); console.log(finalArr); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You could use a hash table for the outer keys and concat the inner values with a dynamic approach for the outer keys, like setter .

 var data = [{ setter: [{ keyname: "Sample Size", cond: "=", value: 1 }] }, { setter: [{ joinedcond: "and" }, { keyname: "Sample Size", cond: "=", value: 2 }] }], result = data.reduce(function (hash) { return function (r, o) { Object.keys(o).forEach(function (k) { if (!hash[k]) { hash[k] = {}; r.push(hash[k]); } hash[k][k] = (hash[k][k] || []).concat(o[k]); }); return r; }; }(Object.create(null)), []); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Using ES6 Rest and Spread operators we can achieve the same with a recursive function call:

let cdata= data.slice();//Copy the data
let condensedArray=[];

function flatten(data, ...rest){
    let [{ setter }] = data; 
    condensedArray = [...condensedArray, ...setter];
    data.splice(0,1); 
    data.length>0?flatten(data, ...data):console.log('Complete');
}

flatten(cdata, ...cdata);
console.log(condensedArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM