我有一个Javascript对象像:

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

如何删除所有未定义的属性?False属性应该保留。


当前回答

我喜欢用_。pickBy,因为你可以完全控制你要删除的东西:

var person = {"name":"bill","age":21,"sex":undefined,"height":null};

var cleanPerson = _.pickBy(person, function(value, key) {
  return !(value === undefined || value === null);
});

来源:https://www.codegrepper.com/?search_term=lodash +删除+未定义值+ + +对象

其他回答

对于那些想要从对象数组中删除并使用lodash的人,你可以这样做:


 const objects = [{ a: 'string', b: false, c: 'string', d: undefined }]
 const result = objects.map(({ a, b, c, d }) => _.pickBy({ a,b,c,d }, _.identity))

 // [{ a: 'string', c: 'string' }]

注意:如果你不想销毁,你不必销毁。

对于深嵌套对象,您可以使用我的代码片段为lodash > 4

const removeObjectsWithNull = (obj) => {
    return _(obj)
      .pickBy(_.isObject) // get only objects
      .mapValues(removeObjectsWithNull) // call only for values as objects
      .assign(_.omitBy(obj, _.isObject)) // save back result that is not object
      .omitBy(_.isNil) // remove null and undefined from object
      .value(); // get value
};

我也会使用下划线并处理空字符串:

Var my_object = {a:undefined, b:2, c:4, d:undefined, k: null, p: false, s: ", z: 0}; Var结果=_。省略(my_object, function(value) { return _.isUndefined(value) || _.isNull(value) || value === "; }); console.log(结果);//对象{b: 2, c: 4, p: false, z: 0}

JSBIN.

正确答案是:

_.omitBy({ a: null, b: 1, c: undefined, d: false }, _.isNil)

结果是:

{b: 1, d: false}

其他人给出的另一种说法:

_.pickBy({ a: null, b: 1, c: undefined, d: false }, _.identity);

也将删除这里不需要的假值。

你也可以使用Object。使用Array.prototype.filter。

const omitNullish = (object) => 
   Object.fromEntries(
       Object.entries(object).filter(([, value]) => value != null)
   )

omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}

如果你想使用lodash,他们从v5中删除了省略,所以另一种选择是使用fp/pickBy以及isNil和negate。

import pickBy from 'lodash/fp/pickBy'
import isNil from 'lodash/isNil';
import negate from 'lodash/negate';


const omitNullish = pickBy(negate(isNil))

omitNullish({ a: null, b: 1, c: undefined, d: false, e: 0 }) // { b: 1, d: false, e: 0}