I have array of objects like below:
checklist= [
{
"participantId": 13,
"rankStatus": "participated",
"rank": 3,
"comment": "my comment",
"horse_name": "test232 fdfgdg",
"country": "Afghanistan",
"life_number": null
},
{
"participantId": 12,
"rankStatus": "eliminated",
"comment": null,
"horse_name": "test horse",
"country": "Algeria",
"life_number": "234234"
},
{
"participantId": 11,
"rankStatus": null,
"rank": null,
"comment": null,
"horse_name": "tesdfs",
"country": "Afghanistan",
"life_number": null
},
{
"participantId": 10,
"rankStatus": null,
"comment": null,
"horse_name": "nam horse",
"country": "India",
"life_number": "fh345"
}
];
In above array of objects, I need to add rank=0 to the objects where rank is not present.
I tried like below, but not able to figure it out correct way of doing this.
checklist.filter(x => !x.hasOwnProperty('rank') ).map(x => x.rank == 0);
What is right way of doing this? Please help and guide. Thanks
I would just do:
checklist.map(item => ({ rank: 0, ...item }))
Since you spread item after rank, if it has a rank the 0 will be overwritten, if it doesn't exist, it will end up with 0 for the rank.
If performance is a concern, it is probably more efficient to do:
checklist.forEach((item) => item.rank = item.rank || 0);