Using spread operator to update an object value

荒凉一梦 提交于 2019-11-27 14:41:18

问题


I have a function which adds a key to incoming object, but I have been told to use spread operator for that, I have been told that I can use the spread operator to create a new object with the same properties and then set isAvailable on it.

  return new Partner(ServerConfig, capabilities, initialState)
}

class Partner {
  constructor (ServerConfig, capabilities, initialState) {
    initialState.isAvailable = true

So I tried something like this but coulndt succeed, can you help me ? and confused, should I use spread operator in this way , return from a function ?

newObject = {}

// use this inside a function and get value from return

   return {
     value: {
       ...newObject,
       ...initialState
     }
   }

initialState.isAvailable = true


回答1:


The properties are added in order, so if you want to override existing properties, you need to put them at the end instead of at the beginning:

return {
  value: {
    ...initialState,
    ...newObject
  }
}

You don't need newObject (unless you already have it lying around), though:

return {
  value: {
    ...initialState,
    isAvailable: newValue
  }
}

Example:

const o1 = {a: "original a", b: "original b"};
// Doesn't work:
const o2 = {a: "updated a", ...o1};
console.log(o2);
// Works:
const o3 = {...o1, a: "updated a"};
console.log(o3);


来源:https://stackoverflow.com/questions/49491393/using-spread-operator-to-update-an-object-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!