I have this object. If a property's value is null I'm removing that property. But I have some special properties that I want to keep no matter what (even if their values are null). So far my code works great, but I don't like the fact that I have to use the OR || operator over and over. Example:
key === 'alwaysCountWithMe' || key === 'ABC' || key ==='doNotDeleteMe' || key === 'specialProperty'
Here's my code:
var object = {
"firstname": null,
"lastname": "White",
"ABC": null,
"hobby": null,
"c": 3,
"alwaysCountWithMe": null,
"doNotDeleteMe": null,
"specialProperty": null,
};
console.log(_.pickBy(object, (value, key) => !!value || key === 'alwaysCountWithMe' || key === 'ABC' || key === 'doNotDeleteMe' || key === 'specialProperty'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Is there a cleaner way of doing this without having to use the || over and over?.
Use an array of keys to always keep, and check to see if it includes(key)
:
var object = {
"firstname": null,
"lastname": "White",
"ABC": null,
"hobby": null,
"c": 3,
"alwaysCountWithMe": null,
"doNotDeleteMe": null,
"specialProperty": null,
};
const alwaysKeep = ['alwaysCountWithMe', 'ABC', 'doNotDeleteMe', 'specialProperty'];
console.log(_.pickBy(object, (value, key) => !!value || alwaysKeep.includes(key)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>