0

I have an object and I want to remove all properties that have a value of null, but I want to keep a special property which is alwaysCountWithMe (even if its value is null). My code looks like this:

var object = {
"firstname": null, 
"lastname": "White", 
"hobby": null,
"c": 3 , 
"alwaysCountWithMe": null
};
console.log(_.pickBy(object, value => !!value));

This prints:

{"lastname": "White", "c": 3}

But I want it to print:

{"lastname": "White", "c": 3, "alwaysCountWithMe": null }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Devmix
  • 1,599
  • 5
  • 36
  • 73
  • I’m guessing you’re using lodash? If it’s underscore, please replace the tag – MTCoster Feb 07 '19 at 23:42
  • Yes, I'm using lodash, what would be your solution to this? – Devmix Feb 07 '19 at 23:43
  • It should be noted that `!!value` will also drop properties with any [falsey value](https://stackoverflow.com/a/19839953/1813169). Use `value !== null` to explicitly detect nulls – MTCoster Feb 07 '19 at 23:51

3 Answers3

1

Expanding on your existing solution, how about this using some new ES6 object syntax:

var object = { firstname: null, lastname: 'White', hobby: null, c: 3, alwaysCountWithMe: null };
console.log({
  ...(_.pickBy(object, value => value !== null)),
  alwaysCountWithMe: object.alwaysCountWithMe
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
MTCoster
  • 5,868
  • 3
  • 28
  • 49
1

It looks like the second argument passed to the pickBy method is the key name, so you could probably change it to:

console.log(_.pickBy(object, (value, key) => !!value || key === 'alwaysCountWithMe'));
Taplar
  • 24,788
  • 4
  • 22
  • 35
1

Just change your function (the second argument of _.pickBy) to take the key argument so you can check if key is alwaysCountWithMe:

var object = {
  "firstname": null,
  "lastname": "White",
  "hobby": null,
  "c": 3,
  "alwaysCountWithMe": null
};

    console.log(_.pickBy(object, (value, key) => !!value || key == "alwaysCountWithMe"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79