Javascript 如何使用 Lodash 从数组中删除对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38704686/
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 21:44:35  来源:igfitidea点击:

How can I remove object from array, with Lodash?

javascriptnode.jslodash

提问by Fábio Zangirolami

I'm trying to remove an object from an array using Lodash.

我正在尝试使用 Lodash 从数组中删除一个对象。

In server.js(using NodeJS):

server.js(使用 NodeJS):

    var lodash = require('lodash')();

    var rooms = [
      { channel: 'room-a', name: 'test' },
      { channel: 'room-b', name: 'test' } 
    ]

I tried with two commands and it did not work:

我尝试了两个命令,但没有用:

    var result = lodash.find(rooms, {channel: 'room-a', name:'test'});
    var result = lodash.pull(rooms, lodash.find(rooms, {channel: 'room-a', name:'test'}));

Here's the output of console.log(result):

这是输出console.log(result)

    LodashWrapper {
      __wrapped__: undefined,
      __actions__: [ { func: [Function], args: [Object], thisArg: [Object] } ],
      __chain__: false,
      __index__: 0,
      __values__: undefined }

Can someone help me? Thank you!

有人能帮我吗?谢谢!

采纳答案by SLaks

require('lodash')()

Calling the lodashfunction (by ()) creates a LoDash object that wraps undefined.

调用lodash函数 (by ()) 会创建一个 LoDash 对象,该对象将undefined.

That's not what you want; you want the lodashfunction itself, which contains static methods.

那不是你想要的;您需要lodash包含静态方法的函数本身。

Remove that.

去掉那个。

回答by Stanislav Ostapenko

_.remove()is a good option.

_.remove()是一个不错的选择。

var rooms = [
  { channel: 'room-a', name: 'test' },
  { channel: 'room-b', name: 'test' } 
];

_.remove(rooms, {channel: 'room-b'});

console.log(rooms); //[{"channel": "room-a", "name": "test"}]
<script src="https://cdn.jsdelivr.net/lodash/4.14.2/lodash.min.js"></script>

回答by Adam Boduch

I'd go for reject()in this scenario. Less code:

在这种情况下,我会选择reject()。更少的代码:

var result = _.reject(rooms, { channel: 'room-a', name: 'test' });