const rowData = [];
const arr1 = [{
"bId": "F1.1.4",
"bName": "Mercedes",
"cId": "150494",
"cName": "Benz",
"flag": "Maintain"
},
{
"bId": "F1.1.4",
"bName": "Ford",
"cId": "150744",
"cName": "Mustang",
"flag": "Maintain"
},
{
"bId": "F1.1.4",
"bName": "Volkswagon",
"cId": "4961",
"cName": "Polo",
"flag": "Maintain"
},
{
"bId": "F1.1.5",
"bName": "Isdera",
"cId": "N/A",
"cName": "Isdera",
"flag": "Test"
}
]
const arr2 = [{
"cId": "150494",
"flag": "Decommission"
},
{
"cId": "150744",
"flag": "Invest"
},
{
"cId": "4961",
"flag": "Pending"
}
]
for (let i = 0; i < arr1.length; i++) {
const obj = {
custId: arr1[i].cId,
custName: arr1[i].cName,
bId: arr1[i].bId,
bufName: arr1[i].bName,
impFlag: arr2.filter(({cId}) => cId === arr1[i].cId).map(({flag}) => (flag)).toString()
};
rowData.push(obj);
}
console.log(rowData)
Hi, I’m checking if cId
in arr2
is present in arr1
and based on it I’m updating the flag for which cId is present, but for the remaining values which are not present in arr2, impFlag is coming as ""
. It should remain the same as in arr1. I’m not sure how to add conditions accordingly??
2
Answers
Since
""
is the only falsy value that you’ll get from callingArray.prototype.toString()
, you can use the||
(OR) operator to provide a default value when there are no matching flags, eg:Above, when
.toString()
results in a falsy""
value, the right-hand side of the||
operator is used as the result instead.Personally, I would write this logic as below. As you’re performing a mapping operator,
.map()
is a good tool for this:You could use
Array.reduce
method instead