Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge JavaScript objects in array with same key

What is the best way to merge array contents from JavaScript objects sharing a key in common?

How can array in the example below be reorganized into output? Here, all value keys (whether an array or not) are merged into all objects sharing the same name key.

var array = [     {         name: "foo1",         value: "val1"     }, {         name: "foo1",         value: [             "val2",             "val3"         ]     }, {         name: "foo2",         value: "val4"     } ];  var output = [     {         name: "foo1",         value: [             "val1",             "val2",             "val3"         ]     }, {         name: "foo2",         value: [             "val4"         ]     } ]; 
like image 325
zdebruine Avatar asked Nov 22 '15 00:11

zdebruine


1 Answers

Here is one option:-

var array = [{    name: "foo1",    value: "val1"  }, {    name: "foo1",    value: ["val2", "val3"]  }, {    name: "foo2",    value: "val4"  }];    var output = [];    array.forEach(function(item) {    var existing = output.filter(function(v, i) {      return v.name == item.name;    });    if (existing.length) {      var existingIndex = output.indexOf(existing[0]);      output[existingIndex].value = output[existingIndex].value.concat(item.value);    } else {      if (typeof item.value == 'string')        item.value = [item.value];      output.push(item);    }  });    console.dir(output);
like image 118
BenG Avatar answered Oct 08 '22 20:10

BenG