繁体   English   中英

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

[英]How can I remove object from array, with Lodash?

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

server.js (使用 NodeJS)中:

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

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

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

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

这是console.log(result)的输出:

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

有人可以帮助我吗? 谢谢!

_.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>

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

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

调用lodash函数(通过() )会创建一个包装undefined的 LoDash 对象。

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

去掉那个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM