简体   繁体   中英

Remove undefined or null fields from json by Lodash

consider following json:

const obj = {
   limit: 0,
   lastName: null,
   firstName: 'John',
   age: undefined
}

I need to remove lastName and age, and keep limit and firstName. I tried this _.pickBy(obj, !_.isNil) but it gives me empty object {} and I don't understand why. What am I doing wrong?

When I tried _.pickBy(obj, _.isNil) then keeps lastName and age, which is correct.

Try omitBy :

 const obj = { limit: 0, lastName: null, firstName: 'John', age: undefined } const res = _.omitBy(obj, _.isNil); console.log(res);
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM