Is there a way to say something like
User.friends[id=1].posts=data
in Javascript, where User.friends is a collection of Friend items, one of whose properties is 'id'?
I am iterating over a collection User.friends, which is a collection of Friend objects that have 3 properties (id, posts, and likes). The inner iterator instance variable, friend, seems passed-by-value not by-reference; so, how do I elegantly set the parent object's properties from within the iterator?
async.each(User.friends, function(friend, cb) {
var url="https://graph.facebook.com/"+friend.id.id+"/?fields=posts&since="+ moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken;
request.get({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
//I WANT TO SET THE ACTUAL User.friend[i].posts value,
//but I do not know how to get the value of 'i'?
friend.posts=body.data; //this just sets local friend var
cb(null);
} else {
console.log(error);
throw error;
}
}); //...request.get
}, function(error, result) {
callback();
}); //...async_each
Sorry if this is a dumb question. Any help really appreciated. I've tried:
_.findWhere(User.friends,{id: friend.id}).posts=body.data;
but this doesn't seem to work (I think it just sets a local value).
You could use the filter method:
var result = User.friends.filter(function(item) { return item.id === 1; })[0].posts = data;