lodash - Javascript merge two objects based on key -


i have objects in shape of below.

[{     product: 'abc',     productid: 'ab123',     batch: 'ba1',     price: '12' }, {     product: 'abc',     productid: 'ab123',     batch: 'ba2',     price: '15' }, {     product: 'xyz',     productid: 'ab124',     batch: 'xy1',     price: '124' }] 

i want merge objects 1 single object in array if key pair (product, , productid) mathced, in below format.

[{     product: 'abc',     productid: 'ab123',     batch: ['ba1', 'ba2'],     price: ['12', '15'] }, {     product: 'xyz',     productid: 'ab124',     batch: 'xy1',     price: '124' }] 

how can in lodash or in pure javascript.

this proposal not alter given data.

it creates new objects, first single data, later if more data should grouped, uses array batch , price.

var data = [{ product: 'abc', productid: 'ab123', batch: 'ba1', price: '12' }, { product: 'abc', productid: 'ab123', batch: 'ba2', price: '15' }, { product: 'xyz', productid: 'ab124', batch: 'xy1', price: '124'}],      merged = [];    data.foreach(function (a) {      if (!this[a.productid]) {          this[a.productid] =  { product: a.product, productid: a.productid, batch: a.batch, price: a.price };          merged.push(this[a.productid]);          return;      }      if (!array.isarray(this[a.productid].batch)) {          this[a.productid].batch = [this[a.productid].batch];      }      if (!array.isarray(this[a.productid].price)) {          this[a.productid].price = [this[a.productid].price];      }      this[a.productid].batch.push(a.batch);      this[a.productid].price.push(a.price);  }, object.create(null));    console.log(merged);


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -