Javascript 如何使用 lodash 从对象中删除未定义和空值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30812765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:47:13  来源:igfitidea点击:

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

javascriptobjectlodash

提问by JLavoie

I have a Javascript object like:

我有一个 Javascript 对象,如:

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

How to remove all the undefined properties? False attributes should stay.

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

回答by ryeballar

You can simply chain _.omit()with _.isUndefinedand _.isNullcompositions, and get the result with lazy evaluation.

您可以简单地_.omit()使用_.isUndefined_.isNull组合链接,并通过延迟评估获得结果。

Demo

演示

var result = _(my_object).omit(_.isUndefined).omit(_.isNull).value();

Update March 14, 2016:

2016 年 3 月 14 日更新

As mentioned by dylantsin the comment section, you should use the _.omitBy()function since it uses a predicate instead of a property. You should use this for lodash version 4.0.0and above.

正如dyants在评论部分提到的,您应该使用该_.omitBy()函数,因为它使用谓词而不是属性。您应该将它用于 lodash 版本4.0.0及更高版本。

DEMO

演示

var result = _(my_object).omitBy(_.isUndefined).omitBy(_.isNull).value();

Update June 1, 2016:

2016 年 6 月 1 日更新

As commented by Max Truxa, lodash already provided an alternative _.isNil.

正如Max Truxa 所说,lodash 已经提供了一个替代方案_.isNil

var result = _.omitBy(my_object, _.isNil);

回答by Tx3

If you want to remove all falseyvalues then the most compact way is:

如果要删除所有falsey值,那么最紧凑的方法是:

For Lodash 4.x and later:

对于Lodash 4.x 及更高版本

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

For legacyLodash 3.x:

对于旧版Lodash 3.x:

_.pick(obj, _.identity);

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

回答by JavaFish

if you are using lodash, you can use _.compact(array)to remove all falsely values from an array.

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

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

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

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

回答by Tiago Bértolo

The correct answer is:

正确答案是:

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

That results in:

这导致:

{b: 1, d: false}

The alternative given here by other people:

其他人在这里给出的替代方案:

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

Will remove also falsevalues which is not desired here.

还将删除false此处不需要的值。

回答by PhiLho

Just:

只是:

_.omit(my_object, _.isUndefined)

The above doesn't take in account nullvalues, as they are missing from the original example and mentioned only in the subject, but I leave it as it is elegant and might have its uses.

上面没有考虑null值,因为它们在原始示例中缺失并且仅在主题中提到,但我保留它,因为它很优雅并且可能有其用途。

Here is the complete example, less concise, but more complete.

这是完整的示例,不那么简洁,但更完整。

var obj = { a: undefined, b: 2, c: 4, d: undefined, e: null, f: false, g: '', h: 0 };
console.log(_.omit(obj, function(v) { return _.isUndefined(v) || _.isNull(v); }));

回答by nSimonFR

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:

要完成其他答案,在 lodash 4 中仅忽略 undefined 和 null(而不是像 那样的属性false),您可以在 中使用谓词_.pickBy

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

_.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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>

回答by Oleg Koval

According to lodash docs:

根据 lodash 文档:

_.compact(_.map(array, fn))

Also you can filter out all nulls

您也可以过滤掉所有空值

回答by 1nstinct

For deep nested object you can use my snippet for lodash > 4

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

回答by d4nyll

Since some of you might have arrived at the question looking to specifically removing onlyundefined, you can use:

由于你们中的一些人可能已经找到了专门删除only的问题undefined,您可以使用:

  • a combination of Lodash methods

    _.omitBy(object, _.isUndefined)
    
  • the rundefpackage, which removes only undefinedproperties

    rundef(object)
    
  • Lodash 方法的组合

    _.omitBy(object, _.isUndefined)
    
  • rundef仅删除undefined属性的包

    rundef(object)
    


If you need to recursivelyremove undefinedproperties, the rundefpackage also has a recursiveoption.

如果您需要递归删除undefined属性,该rundef包还有一个recursive选项。

rundef(object, false, true);

See the documentationfor more details.

有关更多详细信息,请参阅文档

回答by user5672998

with pure JavaScript: (although Object.entries is ES7, Object.assign is ES6; but equivalent ES5 uses Object.keys only should be also doable); also notice v != nullchecks for both null and undefined;

使用纯 JavaScript:(虽然 Object.entries 是 ES7,Object.assign 是 ES6;但等效的 ES5 只使用 Object.keys 应该也是可行的);还要注意v != null对 null 和 undefined 的检查;

> var d = { a:undefined, b:2, c:0, d:undefined, e: null, f: 0.3, s: "", t: false };
undefined
> Object.entries(d)
    .filter(([ k, v ]) => (v != null))
    .reduce((acc, [k, v]) => Object.assign(acc, {[k]: v}), {})
{ b: 2, c: 0, f: 0.3, s: '', t: false }

Edit: this below is the version with ES5 Object.keys only: but generally with ES7 in Node v8 is pretty much enjoyable ;-)

编辑:以下是仅包含 ES5 Object.keys 的版本:但通常在 Node v8 中使用 ES7 非常有趣;-)

> Object.keys(d)
    .filter(function(k) { return d[k] != null; })
    .reduce(function(acc, k) { acc[k] = d[k]; return acc; }, {});
{ b: 2, c: 0, f: 0.3, s: '', t: false }

Update in October 2017: with Node v8 (since v8.3 or so) now it has object spreading construct:

2017 年 10 月更新:使用 Node v8(自 v8.3 左右)现在它具有对象传播结构:

> var d = { a:undefined, b:2, c:0, d:undefined,
    e: null, f: -0.0, s: "", t: false, inf: +Infinity, nan: NaN };
undefined
> Object.entries(d)
    .filter(([ k, v ]) => (v != null))
    .reduce((acc, [k, v]) => ({...acc, [k]: v}), {})
{ b: 2, c: 0, f: -0, s: '', t: false, inf: Infinity, nan: NaN }

or within one reduce only:

或仅在一次减少:

> Object.entries(d)
   .reduce((acc, [k, v]) => (v==null ? acc : {...acc, [k]: v}), {})
{ b: 2, c: 0, f: -0, s: '', t: false, inf: Infinity, nan: NaN }

Update: someone want recursive? isn't that hard either, just need an additional check of isObject, and recursively call itself:

更新:有人想要递归?也不是那么难,只需要额外检查 isObject,并递归调用自身:

> function isObject(o) {
    return Object.prototype.toString.call(o) === "[object Object]"; }
undefined
> function dropNullUndefined(d) {
    return Object.entries(d)
      .reduce((acc, [k, v]) => (
        v == null ? acc :
         {...acc, [k]: (isObject(v) ? dropNullUndefined(v) : v) }
      ), {});
  }
> dropNullUndefined({a: 3, b:null})
{ a: 3 }
> dropNullUndefined({a: 3, b:null, c: { d: 0, e: undefined }})
{ a: 3, c: { d: 0 } }

my conclusion: if pure Javascript can do, I would avoid any third party library dependencies:

我的结论:如果纯 Javascript 可以做到,我会避免任何第三方库依赖项: