javascript - What is the best way in ES6 to merge 2 vectors of objects based on their objects props value? -


given these 2 vectors of objects:

dbvector = [   {name: 'one', qty: 1, id: 'id10'},   {name: 'two', qty: 2, id: 'id20'},   {name: 'three', qty: 3, id: 'id30'},   {name: 'for', qty: 4, id: 'id40'}, ];  localvector = [   {name: 'two', qty: 1, id: 'id20'},   {name: 'for', qty: 1, id: 'id40'}, ]; 

what best way merge them qty's updated based on object id.

result = [   {name: 'one', qty: 1, id: 'id10'},   {name: 'two', qty: 3, id: 'id20'},   {name: 'three', qty: 3, id: 'id30'},   {name: 'for', qty: 5, id: 'id40'}, ]; 

at moment doing way:

const merge = (a, b, id) => a.filter( aa => !b.find ( bb => aa[id] === bb[id]) ).concat(b); result = merge(localvector , dbvector , 'id'); 

but qty's don't added.

you take map , update each element of localvector.

var dbvector = [{ name: 'one', qty: 1, id: 'id10' }, { name: 'two', qty: 2, id: 'id20' }, { name: 'three', qty: 3, id: 'id30' }, { name: 'for', qty: 4, id: 'id40' }],      localvector = [{ name: 'two', qty: 1, id: 'id20' }, { name: 'for', qty: 1, id: 'id40' }],      map = new map(dbvector.map(o => [o.id, o]));    localvector.foreach(o => map.get(o.id).qty += o.qty);    console.log(dbvector);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -