我有一个Javascript对象像:

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

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


当前回答

对于深嵌套对象,您可以使用我的代码片段为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 };

var newObject = _.reject(my_collection, function(val){ return _.isUndefined(val) })

//--> newCollection = { b: 2, c: 4 }

可以这样做

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

var passedKeys = _.reject(Object.keys(my_object), function(key){ return _.isUndefined(my_object[key]) || _.isNull(my_object[key]) })

newObject = {};
_.each(passedKeys, function(key){
    newObject[key] = my_object[key];
});

否则,使用普通JavaScript也可以做到

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

Object.keys(my_object).forEach(function(key){
    if (typeof my_object[key] != 'undefined' && my_object[key]!=null){
        new_object[key] = my_object[key];
    }
});

不要使用假测试,因为不仅“undefined”或“null”会被拒绝,其他假值也会被拒绝,如“false”,“0”,空字符串,{}。因此,为了使其简单易懂,我选择使用上面编码的显式比较。

如果您不想删除假值。这里有一个例子:

obj = {
  "a": null,
  "c": undefined,
  "d": "a",
  "e": false,
  "f": true
}
_.pickBy(obj, x => x === false || x)
> {
    "d": "a",
    "e": false,
    "f": true
  }

最短路径(lodash v4):

_.pickBy(my_object)

为了完成其他答案,在lodash 4中只忽略undefined和null(而不是像false这样的属性),你可以在_.pickBy中使用谓词:

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

例子如下: 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. log)stringify(filteredObject, null, 2)); console.log (filteredObject); < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js " > < /脚本>