javascript 使用 Underscore.js 根据属性从数组中删除对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23914991/
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
Use Underscore.js to remove object from array based on property
提问by user1452494
I have an array of objects in javascript. Each object is of the form
我在 javascript 中有一个对象数组。每个对象的形式
obj {
location: "left", // some string
weight: 0 // can be zero or non zero
}
I want to return a filtered copy of the array where the objects with a weight property of zero are removed
我想返回数组的过滤副本,其中删除了权重属性为零的对象
What is the clean way to do this with underscore?
使用下划线执行此操作的干净方法是什么?
回答by p.s.w.g
You don't even really need underscore for this, since there's the filter
method as of ECMAScript 5:
你甚至不需要为此添加下划线,因为filter
ECMAScript 5有这个方法:
var newArr = oldArr.filter(function(o) { return o.weight !== 0; });
But if you want to use underscore (e.g. to support older browsers that do not support ECMAScript 5), you can use its filter
method:
但是如果你想使用下划线(例如支持不支持 ECMAScript 5 的旧浏览器),你可以使用它的filter
方法:
var newArr = _.filter(oldArr, function(o) { return o.weight !== 0; });
回答by Luke
回答by codebox
This should do it:
这应该这样做:
_.filter(myArray, function(o){ return o.weight; });
回答by alengel
You can also use underscore's reject function.
您还可以使用下划线的拒绝功能。
var newObjects = _.reject(oldObjects, function(obj) {
return obj.weight === 0;
});
回答by Nadeem
Old question but my 2 cents:
老问题,但我的 2 美分:
_.omit(data, _.where(data, {'weight':0}));
回答by Alex Dev
return this.data = _.without(this.data, obj);