I have a scenario where I have 2 objects, and I need to add a new key value pair to only the first matching object of its 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
}
Within Obj1
, when the productId
and consumerId
matches, I want to add a new key value pair from Obj2
that has the same productId
and consumerId
to the first occurrence of 0001
and John
.
I've encountered a roadblock at this point.
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,
};
});
If anyone could provide guidance on how to accomplish this task, I would greatly appreciate it. Thank you in advance
edit: There might be some errors in the dummy data provided