I have a requirement where I want to add null values for properties which are non existent in the array of objects. I don’t want to loop over
var data=[
{
"id": 1,
"name": "John"
},
{
"id": 2
},
{
"id": 3
}
]
Expected result is as follows
[
{
"id": 1,
"name": "John"
},
{
"id": 2,
"name": null
},
{
"id": 3,
"name": null
}
]
3
Answers
Map array so if name is undefined set it to null, otherwise leave the same value:
Little for each loop will do that. Also I think
||
would be better than??
, here is why:When should I use ?? (nullish coalescing) vs || (logical OR)?
Ah sorry, didn’t notice the part with the loop in the question. I still let this answer be here.
One further option is the following, with explanatory comments in the code; this answer assumes that the keys may have to be found prior to adding them to the Object:
JS Fiddle demo.
References:
Array.prototype.flat()
.Array.prototype.map()
.Array.prototype.push()
.Array.prototype.reduce()
.Object.fromEntries()
.Object.keys()
.Set()
.