我有一个Javascript对象像:

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

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


当前回答

如果你想移除所有假值,那么最紧凑的方法是:

对于Lodash 4。X及以后:

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

对于遗留的Lodash 3.x:

_.pick(obj, _.identity);

_.pick({ a: null, b: 1, c: undefined }, _.identity);
>> Object {b: 1}

其他回答

如果使用lodash,可以使用_.compact(array)从数组中删除所有错误值。

_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]

https://lodash.com/docs/4.17.4#compact

为了完成其他答案,在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 " > < /脚本>

用于深嵌套的对象和数组。并从字符串和NaN中排除空值

function isBlank(value) {
  return _.isEmpty(value) && !_.isNumber(value) || _.isNaN(value);
}
var removeObjectsWithNull = (obj) => {
  return _(obj).pickBy(_.isObject)
    .mapValues(removeObjectsWithNull)
    .assign(_.omitBy(obj, _.isObject))
    .assign(_.omitBy(obj, _.isArray))
    .omitBy(_.isNil).omitBy(isBlank)
    .value();
}
var obj = {
  teste: undefined,
  nullV: null,
  x: 10,
  name: 'Maria Sophia Moura',
  a: null,
  b: '',
  c: {
    a: [{
      n: 'Gleidson',
      i: 248
    }, {
      t: 'Marta'
    }],
    g: 'Teste',
    eager: {
      p: 'Palavra'
    }
  }
}
removeObjectsWithNull(obj)

结果:

{
   "c": {
      "a": [
         {
            "n": "Gleidson",
            "i": 248
         },
         {
            "t": "Marta"
         }
      ],
      "g": "Teste",
      "eager": {
         "p": "Palavra"
      }
   },
   "x": 10,
   "name": "Maria Sophia Moura"
}

我喜欢用_。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 +删除+未定义值+ + +对象

省略所有假值,但保留布尔原语,这个解决方案有帮助。

_.omitBy(fields, v => (_.isBoolean(v)||_.isFinite(v)) ? false : _.isEmpty(v));

让田野= str:’CAD’, numberStr:’123’, 123号, boolStrT:’true’, boolStrF:’false’, 假的,假的, 真实, undef: undefined, mo:零, emptyStr:”, 阵列:[1,2,3], emptyArr: [] ); 让诺布= _。omitBy (fields, v = > (_ isBoolean (v) | | _ isFinite (v)) ?伪造:_.isEmpty(v); 游戏机。log (nobj); < script src =“https://cdn.jsdelivr.net/npm/lodash@4。11月17日/ lodash min。主持人" > / < script >