How to remove undefined and null values from an object using lodash?

前端 未结 23 2334
既然无缘
既然无缘 2020-11-29 18:06

I have a Javascript object like:

var my_object = { a:undefined, b:2, c:4, d:undefined };

How to remove all the undefined properties? False

23条回答
  •  情歌与酒
    2020-11-29 18:26

    To complete the other answers, in lodash 4 to ignore only undefined and null (And not properties like false) you can use a predicate in _.pickBy:

    _.pickBy(obj, v !== null && v !== undefined)

    Example below :

    const obj = { a: undefined, b: 123, c: true, d: false, e: null};
    
    const filteredObject = _.pickBy(obj, v => v !== null && v !== undefined);
    
    console.log = (obj) => document.write(JSON.stringify(filteredObject, null, 2));
    console.log(filteredObject);

提交回复
热议问题