我有一个JavaScript对象数组,每个对象的形式为
obj {
location: "left", // some string
weight: 0 // can be zero or non zero
}
我希望能返回一个过滤后的数组副本,其中具有权重属性为零的对象被移除。
使用underscore,最好的方法是什么?
我有一个JavaScript对象数组,每个对象的形式为
obj {
location: "left", // some string
weight: 0 // can be zero or non zero
}
filter
可以完成这项工作。
_.filter(data, function(item) { return !!item.weight; });
!!
用于将item.weight
转换为布尔值,其中NULL
、false
或0
将使其变为false
并将其过滤掉。
_.filter(myArray, function(o){ return o.weight; });
var newObjects = _.reject(oldObjects, function(obj) {
return obj.weight === 0;
});
老问题,但我想发表我的意见:
_.omit(data, _.where(data, {'weight':0}));
return this.data = _.without(this.data, obj);