-1

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

itsMe
  • 133
  • 12
  • Obj1 is an array, not an object. There's never a `Obj1.consumerId`, only a `Obj1[i].consumerId`. Also has nothing to do with React, please don't add unrelated tags to your questions. –  Mar 18 '22 at 10:27
  • thanks for the info and the down vote, I'm just trying to learn JS @ChrisG – itsMe Mar 18 '22 at 10:30
  • Sorry, but stackoverflow is not a tutorial website. It's a last resort kind of deal. [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/5734311) –  Mar 18 '22 at 10:32
  • I know, that's why I went here to ask. And not even tryin to get the whole code here, just a little bit of idea how to get this works – itsMe Mar 18 '22 at 10:36
  • Duplicate: [Array.push() if does not exist?](https://stackoverflow.com/questions/1988349/array-push-if-does-not-exist) –  Mar 18 '22 at 10:44

1 Answers1

1

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);
Salman A
  • 262,204
  • 82
  • 430
  • 521