let original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};
happyBirthday will be an object that is identical to original but with the age overwritten.
So that would result in an object like this:
{name: 'Joel', favoriteFood: 'oranges', age: 27} // Notice the age
Answer from Pedro Filipe on Stack OverflowSpread Operator(Object inside Object)
javascript - Quick question about ES6 spread operator on objects - Stack Overflow
Adding arbitrary attributes to object using spread operator
Spread-object operator missing in kotlin? - Language Design - Kotlin Discussions
Videos
let original = {name: 'Joel', favoriteFood: 'oranges', age: 26};
let happyBirthday = {...original, age: 27};
happyBirthday will be an object that is identical to original but with the age overwritten.
So that would result in an object like this:
{name: 'Joel', favoriteFood: 'oranges', age: 27} // Notice the age
Objects cannot have duplicate keys. If you assign a key to an object when that object already has said key, or write an object initializer with duplicate keys, the prior value at that key will be overwritten:
const obj = {
foo: 'foo',
bar: 'bar',
};
obj.foo = 'new';
console.log(obj);
const obj = {
foo: 'foo',
bar: 'bar',
foo: 'new',
};
console.log(obj);
When using object spread, the same sort of thing is going on. If you add a key-value pair when a prior key already exists in the object initializer (by spread or otherwise), the prior value will be overwritten.
let happyBirthday = {...original, age: 27};
is very similar to
// Create a new object with all properties of `original`:
let happyBirthday = Object.assign({}, original);
// Assign to the `age` property of the new object:
happyBirthday.age = 27;
Why is it possible to add arbitrary attributes to an object? This should throw a Typescript error in my opinion.
type Params = {
limit: number;
}
// Does not work
const params: Params = {
limit: 20,
q: "john"
}
// Does work
const spreadParams: Params = {
limit: 20,
...({ q: "john" })
};
console.log(spreadParams.q);
// 'john'https://www.typescriptlang.org/play/?ssl=18&ssc=10&pln=1&pc=1#code/C4TwDgpgBACghgJzgWwM5QLxQN4CgoFQA2AlsicAFxQB2ArsgEYQIDcuAvrrgPQ9QARAPYR0NIcCgB3IQgDWuAMZCaqSWEQpU1eEjSYc+QqXJUoAJgAMAGiMEAjtQBEAKyEALGk87c+gkegy8koqalCoYAgQcAAmulo6mvpYeITEZBTUVrZpAHT5ABTYUI5Qrh5eUBwAlJzsIapCRBC5REIA5gURUbHxaLn21ex+AORuniO4QA