Home > OS >  JS Object append and only add new value to the first object
JS Object append and only add new value to the first object

Time:03-18

I have 2 objects, and I want to add a new key value pair to only the first match object of it's kind.

Obj1
[{
buyDate: "yesterday",
productId: "0001",
consumerId: "John",
price: 10
// add new key value pair here
},
{
buyDate: "today",
productId: "0001",
consumerId: "John",
price: 10
},
{
buyDate: "yesterday",
productId: "0002",
consumerId: "Doe",
price: 7
}]
Obj2
{
productId: "0001",
consumerId: "John",
quantity: 4
}

In Obj1, since the productId and the consumerId are the same, I want to add a new key value pair from Obj2 that has the same productId and consumerId to the first 0001 and John.

I got stuck from here.

     let newObj2 = {};
      if (Obj1) {
        Obj1.forEach((e) => {
          newObj2[e.consumerId] = e;
        });
      }

      let newData = Obj1.map((e) => {
        return {
          ...e,
          quantity: Obj2[e.consumerId]?.quantity
            ? Obj2[e.consumerId]?.quantity
            : 0,
        };
      });

Could anyone give me some help how to achieve that? Appreciate any kinda response. Thanks before

edit: since it's a dummy data I wrote some mistake

CodePudding user response:

Use Array.find to find the item in the array being searched like so:

const obj1 = [
  { buyDate: "yesterday", productId: "0001", consumerId: "John", price: 10 },
  { buyDate: "today", productId: "0001", consumerId: "John", price: 10 },
  { buyDate: "yesterday", productId: "0002", consumerId: "Doe", price: 7 }
];
const obj2 = {
  productId: "0001", consumerId: "John", quantity: 4
};
let item = obj1.find(function(item) {
  return item.productId === obj2.productId && item.consumerId === obj2.consumerId
});
if (item === undefined) {
  // not found
} else {
  item.quantity = obj2.quantity;
}
console.log(obj1);

  • Related