Mengingat 2 vektor objek ini:

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'},
];

Apa cara terbaik untuk menggabungkannya sehingga qty diperbarui berdasarkan id objek.

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'},
];

Saat ini saya melakukannya dengan cara ini:

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

Tetapi qty tidak ditambahkan.

1
UnuSec 15 Agustus 2017, 13:08

2 jawaban

Jawaban Terbaik

Anda dapat mengambil Map dan perbarui dengan setiap elemen 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; }
3
Nina Scholz 15 Agustus 2017, 10:24

Anda bisa menggunakan sesuatu seperti

let 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'},
];

let localVector = [
  {name: 'two', qty: 1, id: 'id20'},
  {name: 'for', qty: 1, id: 'id40'},
];

function searchLocalVector(name, id){
  let idx = 0;
  for(let obj of localVector){
    if(obj.name == name && obj.id == id){
      return idx;
    }
    idx++;
  }
  return -1;
}

for(let i=0;i <dbVector.length; i++){
  let idx = searchLocalVector(dbVector[i].name, dbVector[i].id);
  while(idx > -1){
    dbVector[i].qty += localVector[idx].qty;
    localVector.splice(idx, 1);
    idx = searchLocalVector(dbVector[i].name, dbVector[i].id);
  }
}

dbVector.concat(localVector);

console.log(dbVector)
0
marvel308 15 Agustus 2017, 10:21