Reputation: 435
I have an array of objects. I want to filter them and then do something to the filtered objects. This is my attempt so far.
Positions Object
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
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
}
Upvotes: 1
Views: 6326
Reputation: 1543
You need your filter callback to return true/false. You want to return true when the current item should be included in the resulting array and false if it should be excluded. So if you want to filter where obj.set === "brown", do:
var filtered = positions.filter(function(obj){
if (obj.set === "brown") {
obj.owner = "me"; // your additional action to perform
return true;
}
return false;
});
As 'just somebody' notes in the comments, It is generally bad practice to make filter do anything other than the filtering part. But this above example shows you how to do this inside of the filter per your original question.
Upvotes: 0
Reputation: 19257
var set = "brown"
var filtered = positions
.filter(function (obj)
{
return obj.set === "brown"
})
.map(function (obj)
{
obj.owner = me
return obj
})
;
console.log(filtered);
Upvotes: 3
Reputation: 302
What about the jQuery .each()
function ?
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";
});
}
Upvotes: 0