Javascript 使用扩展运算符更新对象值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49491393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using spread operator to update an object value
提问by Rasim Avc?
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.
我有一个函数可以为传入的对象添加一个键,但有人告诉我为此使用扩展运算符,有人告诉我可以使用扩展运算符创建一个具有相同属性的新对象,然后在其上设置 isAvailable .
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
// 在函数中使用 this 并从返回值中获取值
return {
value: {
...newObject,
...initialState
}
}
initialState.isAvailable = true
initialState.isAvailable = true
回答by T.J. Crowder
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:
不过,您不需要newObject(除非您已经拥有它):
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);
回答by Brent Washburne
If you know the name of the property (ain the example below), then @crowder's answer is perfect:
如果您知道属性的名称(a在下面的示例中),那么@crowder 的答案是完美的:
const o3 = {...o1, a: "updated a"};
console.log(o3);
If the property name is in a variable, then you need to use Computed Property namessyntax:
如果属性名称在变量中,则需要使用计算属性名称语法:
let variable = 'foo'
const o4 = {...o1, [variable]: "updated foo"};
console.log(o4);

