Reputation: 3239
this.users = this.users.map(oldUser => oldUser.id === user.id ? user : oldUser);
above code is to splice in updated user's data into users object, but in the same time I also wanted to add extra property into user object, I tried
this.users = this.users.map(oldUser => {
if(oldUser.id === user.id){
user.updated = 'grade';
return user
}else{
return oldUser
}
});
but seeing array of object within array of object, I guess my map messed up
Upvotes: 0
Views: 88
Reputation:
I can't comment that's why I m writing in answer. map function can't be used on object. To use map function you should convert object into an array then you can use map.
Upvotes: 0
Reputation: 19060
Using Array.prototype.map().
Code:
const users = [{id: 1}, {id: 2}, {id: 3}],
user = {id: 1};
users.map((u) => u.id === user.id ? (u.updated = 'grade') : u);
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 19049
A working example (where users
simulate this.users
and user
this.user
):
let users = [{id:'foo'}, {id:'bar'}];
const user = {id:'bar'};
users = users.map((oldUser) => (user.id === oldUser.id) ? Object.assign({}, oldUser, {updated:'grade'}) : oldUser);
Upvotes: 1
Reputation: 138234
You may want this ( if ids are unique) :
user.updated="grade";
this.users[this.users.findIndex(u=>u.id===user.id)]=user;
Much better then remapping all users...
Upvotes: 0