【问题标题】:Adding object when nested in Javascript with ES6使用 ES6 嵌套在 Javascript 中时添加对象
【发布时间】:2019-09-02 17:20:39
【问题描述】:

我正在尝试添加一个对象,但它似乎被覆盖而不是被添加。

我有一个初始对象:

const config = {
    person: 'Bob',
    employer: 'yahoo',
}

我正在其他地方制作一个新对象,如下所示:

const newConfig = {
        ...config,
        customText: { [myVar]: messageText },
        [myVar]: selectedItem,
      };

myVar 可以是发送给 Bob 的 messagenote

首先,你给 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


    【解决方案1】:

    你也需要传播customText,否则它每次都会用新属性替换customText

    const newConfig = {
            ...config,
            customText: {...config.customText, [myVar]: messageText },
            [myVar]: selectedItem,
    };
    

    【讨论】:

    • 谢谢!所以这是传入旧值和新值,并且都分配给 customText。明白了!
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2013-11-07
    • 2021-11-16
    • 1970-01-01
    • 2020-11-03
    • 2012-10-05
    相关资源
    最近更新 更多