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);
Answer from T.J. Crowder on Stack OverflowThe 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);
If you know the name of the property (a in the example below), then @crowder's answer is perfect:
const o3 = {...o1, a: "updated a"};
console.log(o3);
If the property name is in a variable, then you need to use Computed Property names syntax:
let variable = 'foo'
const o4 = {...o1, [variable]: "updated foo"};
console.log(o4);
b is overwritten:
const shared = { a : { b : 1 } }
const added = { ...shared, a : { c : 2 } }
console.log(added);Actual use case is below. I was testing the above in JSBin because I thought this might be a concern.
How can I avoid overwriting b (or voice in my real example)? I want to set the ssmlGender in shared options, but not the languageCode.
I'm thinking I might have to set properties one by one using dot or bracket notation? Or is there a more concise way?
const sharedOptions = {
, voice : { languageCode : "", ssmlGender : voiceGender.male }
, audioConfig : {audioEncoding : "OGG_OPUS"}
}
const foreignAudioOptions = {
...sharedOptions
, input : {text : ""}
}
const englishAudioOptions = {
...sharedOptions
, input : {text : ""}
}You spread syntax on right hand side.
Note: Use Spread Operator first then set the new property. For example {c:'D',...foo} will not work.
let foo = {a: 'A', b: 'B', c: 'C'};
let res = {...foo, c:'D'};
console.log(res)
You would write your code like this:
var obj1 = {a: 'A', b: 'B', c: 'C'}
var obj2 = {...obj1, c: 'D'}
console.log(obj2)
Writing ...obj1 will fill obj2 with obj1's contents, and writing c: 'D' will overwrite c: 'c'.
Note, ordering is important, as maheer mentioned, because the object will be written in order, from each property, which can mess up ordering of keys, and setting incorrect values:
var obj = {a: 'A', b: 'B', c: 'C'}
var ex1 = {...obj, c: 'D'}
var ex2 = {c: 'D', ...obj}
var ex3 = {c: 'D', ...obj, c: 'E'}
console.log('Example 1:', ex1)
console.log('Example 2:', ex2)
console.log('Example 3:', ex3)