简体   繁体   中英

Spread operator in object condition on it existing

Consider the following Object that make use of the spread operator in ES6:

{
  index: {
    ...builderVal,
    choices: {
      ...builderVal.choices,
      [field.key]: {
        ...builderVal.choices[field.key],
        choice: e.target.value
      }
    }
  }
}

Here, field.key is a computed value, it may be 0 or 1 or any positive integer number while builderVal acts like a local state dictionary. This code works for the most part except when builderVal.choices doesn't yet exist (for example, on an initialization, or on first mount).

Notice that on first mount, ...builderVal.choices would be undefined and so up to the fifth line of code no exception would throw up. But on the seventh line of code, because ...builderVal.choices is undefined , the following line:

...builderVal.choices[field.key]

Will result in the error (assuming field.key is 0):

Cannot read property '0' of undefined

So my initial thought, being very new to JavaScript is to use like a ternary operator or an AND operator to first check that it exist, something like (pseudo-code):

{
  // truncated 
  [field.key]: {
        builderVal.choices && ...builderVal.choices[field.key],
        choice: e.target.value
      }
}

But this obviously don't work. Anything that point me in the right direction is greatly appreciated.

You have to apply the spread to the whole thing:

 [field.key]: {
        ...(builderVal.choices && builderVal.choices[field.key]),
        choice: e.target.value
      }

or

 [field.key]: {
        ...builderVal.choices?.[field.key],
        choice: e.target.value
      }

If builderVal.choices is undefined, then nothing will be inserted ( ...undefined is a no-op).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM