Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading