0

I have an object called added that looks like this:

{
  title: "test1",
  startDate: "Mon Apr 15 2019 10:30:00 GMT-0500 (Central Daylight Time)",
  endDate: "Mon Apr 15 2019 11:00:00 GMT-0500 (Central Daylight Time)",
  allDay: false
}

I was trying edit the startDate and endDate field of this object by doing:

added = {
  ...added,
  {added.startDate: "111", added.endDate: "222"}       
}

But this gives me an error that says

unexpected token, expected ,

What is the right way of doing this?

Matt
  • 2,063
  • 1
  • 14
  • 35
Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • Possible duplicate of [Using spread operator to update an object value](https://stackoverflow.com/questions/49491393/using-spread-operator-to-update-an-object-value) – Dan O Apr 14 '19 at 22:41

1 Answers1

5

When reassigning added as a new object literal, everything inside the {}s needs to be key-value pairs, or it needs to spread (with ...) an object with key-value pairs into the new object. You can't put a plain object into an object literal (unless you spread it), because an object is a value, not a key-value pair.

Change to:

added = {
  ...added,
  startDate: "111",
  endDate: "222"
}

You could also do

added = {
  ...added,
  ...{
    startDate: "111",
    endDate: "222"
  }
}

which would be valid syntax (but silly do to - easier to just list the new properties in the outer object literal).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320