0

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?

1 Answer 1

4

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,
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! So this is passing in the old value and the new value and both assigning to customText. Got it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.