I have an array of objects as below:
const arr = [{
id: 1,
name: 'John',
lastName: 'Smith’,
note: null
},
{
id: 2,
name: 'Jill',
lastName: null,
note: ‘note 2’
},
{
id: 3,
name: null,
lastName: ’Smith’,
note: null
}
];
I want to remove all null properties/keys from all the objects, except note
. Note is a. non mandatory field in the ui. There are methods in ramda library which can help us remove null keys from objects. But is there a way to selectively preserve some keys even when they are null. Could anyone pls let me know.
the expected output is as below:
[{
id: 1,
name: 'John',
lastName: 'Smith’,
note: null
},
{
id: 2,
name: 'Jill',
note: ‘note 2’
},
{
id: 3,
lastName: ’Smith’,
note: null
}
];
I have tried using the following code:
arr.forEach((obj) => {
if (obj.lastName === null) {
delete obj.lastName;
}
if (obj.firstName === null) {
delete obj.firstName;
}
});
return arr;
The above code works fine for limited amount of keys. But if there are lot of keys the code becomes cumbersome.
thanks