使用扩展运算符更新对象值

我有一个函数,它为传入的对象添加一个键,但是我被告知要使用扩展运算符,我被告知我可以使用扩展运算符来创建一个具有相同属性的新对象,然后在它上面设置 isCompleable。

  return new Partner(ServerConfig, capabilities, initialState)
}


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

所以我尝试这样做,但不能成功,你能帮助我吗?和困惑,我应该这样使用扩展运算符,从一个函数返回?

newObject = {}


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


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


initialState.isAvailable = true
116094 次浏览

这些属性被添加了 按顺序,所以如果你想覆盖现有的属性,你需要把它们放在结尾而不是开头:

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

不过,你不需要 newObject(除非你已经有了它) :

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

例如:

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);

如果你知道属性的名称(下面例子中的 a) ,那么@Crowder 的回答是完美的:

const o3 = {...o1, a: "updated a"};
console.log(o3);

如果属性名在变量中,则需要使用 计算机财产名称语法:

let variable = 'foo'
const o4 = {...o1, [variable]: "updated foo"};
console.log(o4);