Search code examples
javascriptobjectnestedjavascript-objectsassign

Adding object when nested in Javascript with ES6


I am trying to add an object, but it seems like it is overwriting instead of being added.

I have an initial object:

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

I'm making a new object elsewhere like so:

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

myVar can be either message or note that gets sent to Bob.

First, you write a message to Bob, so newConfig looks like this:

const config = {
    person: 'Bob',
    employer: 'yahoo',
    customText: { message: 'hi bob!' }
}

But then later I add a note, and I want the result to be:

const config = {
    person: 'Bob',
    employer: 'yahoo',
    customText: { message: 'hi bob!', note: 'please leave a message for Bob' }
}

Instead, it seems like my object is being overwritten.

const config = {
    person: 'Bob',
    employer: 'yahoo',
    customText: { note: 'please leave a message for Bob' }
}

I've tried to use Object.assign, but I end up in a similar conundrum.

const customText = Object.assign({}, newConfig.customText, {[myVar]: messageText});

I've also tried doing something with the object assignation:

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

But I'm getting an Parsing error: Unexpected token, expected ","

How can I add the object without overwriting it?


Solution

  • You need to spread customText too, else it replaces the customText with new property everytime

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