this.users = this.users.map(oldUser => oldUser.id === user.id ? user : oldUser);
上面的代码是将更新后的用户数据拼接到users对象中,但同时我也想在user对象中添加额外的属性,我尝试了
this.users = this.users.map(oldUser => {
if(oldUser.id === user.id){
user.updated = 'grade';
return user
}else{
return oldUser
}
});
但是看到对象数组中的对象数组,我猜我的 map 搞砸了
最佳答案
一个工作示例(其中users
模拟this.users
和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);
关于javascript - 将对象属性添加到 map 函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846789/