【发布时间】:2019-09-02 17:20:39
【问题描述】:
我正在尝试添加一个对象,但它似乎被覆盖而不是被添加。
我有一个初始对象:
const config = {
person: 'Bob',
employer: 'yahoo',
}
我正在其他地方制作一个新对象,如下所示:
const newConfig = {
...config,
customText: { [myVar]: messageText },
[myVar]: selectedItem,
};
myVar 可以是发送给 Bob 的 message 或 note。
首先,你给 Bob 写一个message,所以 newConfig 看起来像这样:
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { message: 'hi bob!' }
}
但后来我添加了一个注释,我希望结果是:
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { message: 'hi bob!', note: 'please leave a message for Bob' }
}
相反,我的对象似乎被覆盖了。
const config = {
person: 'Bob',
employer: 'yahoo',
customText: { note: 'please leave a message for Bob' }
}
我尝试使用 Object.assign,但最终遇到了类似的难题。
const customText = Object.assign({}, newConfig.customText, {[myVar]: messageText});
我也尝试过使用对象分配做一些事情:
const newConfig = {
...config,
customText[myVar]: messageText,
[myVar]: selectedItem,
};
但我收到了Parsing error: Unexpected token, expected ","
如何添加对象而不覆盖它?
【问题讨论】:
标签: javascript object nested javascript-objects assign