使用UnderscoreJS从数组中删除项目 [英] Remove an item from array using UnderscoreJS

查看:143
本文介绍了使用UnderscoreJS从数组中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这段代码


var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];

我想从数组中删除id = 3的项目。有没有办法在没有拼接的情况下做到这一点? Maye使用下划线或类似的东西?

谢谢!

and I want to remove the item with id = 3 from the array. Is there a way of doing this without splicing? Maye something using underscore or something like that?

Thanks!

推荐答案

只需使用纯JavaScript,这已经是已经回答:按对象属性从数组中删除对象

Just using plain JavaScript, this has been answered already: remove objects from array by object property.

使用underscore.js,您可以将 .findWhere .without

Using underscore.js, you could combine .findWhere with .without:

var arr = [{
  id: 1,
  name: 'a'
}, {
  id: 2,
  name: 'b'
}, {
  id: 3,
  name: 'c'
}];

//substract third
arr = _.without(arr, _.findWhere(arr, {
  id: 3
}));
console.log(arr);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

虽然,既然你在这种情况下创建了一个新数组,你可以简单地使用 _。过滤器或本机 Array.prototype.filter 函数(就像其他问题中所示)。然后你只会迭代一次数组,而不是像这里一样两次。

Although, since you are creating a new array in this case anyway, you could simply use _.filter or the native Array.prototype.filter function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.

如果你想修改数组就地,你有使用 .splice 。这也显示在另一个问题中,非核心似乎没有为此提供任何有用的功能。

If you want to modify the array in-place, you have to use .splice. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.

这篇关于使用UnderscoreJS从数组中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆