0

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

Ashy Ashcsi
  • 1,529
  • 7
  • 22
  • 54
  • 4
    And what have you attempted? Please add that code to your question as a [mcve]. – Andy Oct 12 '22 at 13:39
  • 1
    [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141) – adiga Oct 12 '22 at 13:46
  • 1
    [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/a/261593/3082296) – adiga Oct 12 '22 at 13:46
  • 1
    https://codesandbox.io/s/stackquestion-1-vxus33?file=/src/index.js – Garo Gabrielyan Oct 12 '22 at 13:48
  • I don't know why this hasn't been reopened, as it seems a decent enough question after the edits. You could do this: `const removeNullsExcept = (exceptions) => (o) => Object .fromEntries (Object .entries (o) .filter (([k, v]) => v !== null || exceptions .includes (k)))`, or if you really wanted a Ramda solution: `const removeNullsExcept = (exceptions) => pipe (toPairs, filter (pipe (evolve ([flip (includes) (exceptions), complement (isNil)]), apply (or))), fromPairs)`. In either case, you could call it like this: `arr .map (removeNullsExcept (['note']))` – Scott Sauyet Oct 24 '22 at 13:11

0 Answers0