Let we have two array of objects as,
let oldArrayOfObject = [
{
Item: "ACC",
Price: "",
hasPrice: false,
},
{
Item: "BCC",
Price: "",
hasPrice: false,
},
{
Item: "CCC",
Price: "",
hasPrice: false,
},
{
Item: "DCC",
Price: "",
hasPrice: false,
},
{
Item: "ECC",
Price: "",
hasPrice: false,
},
];
let newArrayOfObject = [
{
Item: "ACC",
Price: 12,
},
{
Item: "BCC",
Price: 50,
},
{
Item: "ECC",
Price: 21,
}
];
Compare two array of objects and if price exists in newArrayOfObject for particular Item insert price into oldArrayOfObject for that particular item and set hasPrice: true.
Expected O/P:
console.log(oldArrayOfObject)
[
{
Item: "ACC",
Price: 12,
hasPrice: true,
},
{
Item: "BCC",
Price: 50,
hasPrice: true,
},
{
Item: "CCC",
Price: "",
hasPrice: false,
},
{
Item: "DCC",
Price: "",
hasPrice: false,
},
{
Item: "ECC",
Price: 21,
hasPrice: true,
},
];
For this I tried as,
const modifiedArrayOfObject = newArrayOfObject.map((node) => {
const oldInfo = oldArrayOfObject.find((item) => item.Item === node.Item);
if (oldInfo) {
return { ...node, hasPrice: oldInfo.Price !== node.Price }
} else {
return { ...node, hasPrice: true };
}
});
But I am unable to move forward from here. Please let me know if anyone needs any further explanation or further clearance.