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
How can I remove object from array, with Lodash?
提问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 lodash
function (by ()
) creates a LoDash object that wraps undefined
.
调用lodash
函数 (by ()
) 会创建一个 LoDash 对象,该对象将undefined
.
That's not what you want; you want the lodash
function 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>