I have two different types of data structures
var dataA = [
{
"Employee Name": "Mr. X",
id: "1"
},
{
"Employee Name": "Mr. Y",
id: "2"
},
{
"Employee Name": "Mr. Z",
id: "3"
}
];
var dataB = [
{
id: "1",
"Portfolio Lead": "A"
},
{
id: "2",
"Portfolio Lead": "B"
},
{
id: "4",
"Portfolio Lead": "D"
}
];
My goal is to compare the id
values of both arrays and include the "Portfolio Lead"
property in dataA
.
Here is my current method,
function mergeTwoArray() {
dataA.forEach(row => {
dataB.forEach(lead => {
if (lead["id"] === row["id"]) {
row["Portfolio Lead"] = lead["Portfolio Lead"];
}
});
});
console.log(dataA);
}
The issue I'm facing is that when the id
does not match, I want to add "#NA"
as the value for "Portfolio Lead"
. However, including an if statement results in all objects having "Portfolio Lead"
set to #NA
.
If you can help point out what I'm doing wrong here, I would greatly appreciate it.
For a live example, please refer to this stackBlitz link https://stackblitz.com/edit/typescript-nypqge?file=index.ts
The desired output should be:
var dataA = [
{
"Employee Name": "Mr. X",
id: "1",
"Portfolio Lead": "A"
},
{
"Employee Name": "Mr. Y",
id: "2",
"Portfolio Lead": "B"
},
{
"Employee Name": "Mr. Z",
id: "3",
"Portfolio Lead": "#NA"
}
];