如果没有提供所有对象键,如何使用给定值更新对象



如果我有一个给定的对象,类型为user:

用户对象

{
id: 001,
email: 'test.user@example.com',
password: '$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6',
firstname: 'Test',
lastname: 'User',
lastlogin: null,
authfailures: 0,
disabled: false,
confirmed: true,
permissions: [],
groups: [],
emailNotifications: false
}

我还有另一个对象,在这个例子中是从一个表单返回的,我想用它更新上面用户对象的属性:

表单结果

{
email: 'test.user2@example.com',
firstname: 'Updated',
lastname: 'Updated2',
groups: ['test', 'test2']
}

在不手动设置每个属性的情况下,如何使用表单的返回值更新用户对象中的值?我希望用户值具有以下值:

期望结果

{
id: 001,
email: 'test.user2@example.com',
password: '$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6',
firstname: 'Updated',
lastname: 'Updated2',
lastlogin: null,
authfailures: 0,
disabled: false,
confirmed: true,
permissions: [],
groups: ['test', 'test2'],
emailNotifications: false
}

无需这样做:

user.firstname = formResults.firstname
user.lastname = formResults.lastname
user.email = formResults.email
user.groups = formResults.groups

有没有一种方法可以用来修补给定的属性?

您可以使用解构:

const baseObject = {
id: 001,
email: 'test.user@example.com',
password: '$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6',
firstname: 'Test',
lastname: 'User',
lastlogin: null,
authfailures: 0,
disabled: false,
confirmed: true,
permissions: [],
groups: [],
emailNotifications: false
};
const newProps = {
email: 'test.user2@example.com',
firstname: 'Updated',
lastname: 'Updated2',
groups: ['test', 'test2']
}
const updatedObject = {
...baseObject,
...newProps
};

您也可以在baseObject上执行同样的操作,但我建议您保持代码不变。

我发现我可以使用Object.assign()

像这样:Object.assign(user, formResults);

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

最新更新