2014-02-28 145 views
1

我有一個對象數組。我想過濾它們,然後對過濾的對象執行一些操作。這是我迄今的嘗試。更新數組中的過濾對象

持倉對象

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

你可以顯示你的「城市」對象嗎? – Praveen

+0

@praveen我編輯了我的問題以顯示City對象。 – Elton

回答

0

你需要你的過濾器的回調,返回真/假。噹噹前項目應該包含在結果數組中時,您希望返回true,如果應該排除它,則返回false。所以,如果你要過濾其中obj.set ===「棕色」,這樣做:

var filtered = positions.filter(function(obj){ 
    if (obj.set === "brown") { 
     obj.owner = "me"; // your additional action to perform 
     return true; 
    } 
    return false; 
}); 

爲'只是某人在評論中指出,這是一般不好的做法,使過濾器做得比過濾其他任何部分。但是,上面的這個例子向你展示瞭如何在你的原始問題的過濾器內部執行此操作。

+1

實際上,'filter'很好,因爲它(通過名稱)只是一件事。你應該離開'// do something'來通過帶有'.map'的過濾數組。 '.filter(function(o){return o.set =='brown'})。map(function(o){mangle(o)})'' –

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); 
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"; 
    }); 

}