我有一个对象数组。我想过滤它们,然后对过滤的对象做一些事情。这是我到目前为止的尝试。
定位对象
function Position (title, type, purchasable){
this.title = title;
this.type = type;
this.purchasable = purchasable || false;
}
function Purchasable (prices){
this.owner = "unowned";
this.rating = 0;
this.prices = prices;
this.price = this.prices[this.rating];
}
function City (title,set,prices){
Position.call(this, title, "city", true);
Purchasable.call(this, prices);
this.set = set;
}
positions = [
new City("Cairo", "brown", [60,2,10,30,90,160,250]),
new City("Vienna", "brown", [60,4,20,60,180,320,450]),
new City("Vienna", "blue", [60,4,20,60,180,320,450])
];
});
功能
function test() {
var set = "brown";
positions.filter(function(obj){
obj.set === "brown"; //do something to every brown set, eg owner = me
});
//I want to change the values of the objs in positions array
}
答案 0 :(得分:0)
您需要使用过滤器回调来返回true / false。当当前项应包含在结果数组中时,您希望返回true,如果应该排除它,则返回false。因此,如果你想过滤obj.set ===“brown”的地方,请执行:
var filtered = positions.filter(function(obj){
if (obj.set === "brown") {
obj.owner = "me"; // your additional action to perform
return true;
}
return false;
});
正如评论中的“只是某人”注释一样,过滤器除了过滤部分之外还要做任何其他操作通常是不好的做法。但是上面的例子向您展示了如何根据原始问题在过滤器内部执行此操作。
答案 1 :(得分:0)
var set = "brown"
var filtered = positions
.filter(function (obj)
{
return obj.set === "brown"
})
.map(function (obj)
{
obj.owner = me
return obj
})
;
console.log(filtered);
答案 2 :(得分:0)
jQuery .each()
函数怎么样?
https://api.jquery.com/each/
function test() {
var set = "brown";
var filtered = positions.filter(function(obj){
obj.set === "brown"; //do something to every brown set, eg owner = me
}).each(function(index, item){
//do something with the object here; your objects are the item parameter
obj.owner = "me";
});
}