So you already try to create new objects rather than mutating current ones because you like your JavaScript to be functional.
javascript
const foo = { id: 1, name: 'Etch' };
const bar = Object.assign({}, foo);
// bar = { id: 1, name: 'Etch' };
Well the object rest spread syntax lets you do this in a little bit of a nicer way.
javascript
const bar = { ...foo };
This one is still in the proposal stages so you’ll need to use babel or something similar to make it work.
Hey this rest spread thing also works with arrays!
javascript
const foo = [1, 2, 3, 4];
const bar = [ ...foo ];
// bar = [1, 2, 3, 4];
You can use this where you would have used Array.push or Array.concat
javascript
const foo = [1, 2];
const bar = [3, 4];
const baz = [...foo, ...bar];
// baz = [1, 2, 3, 4];
Merging objects
Permalink to "Merging objects" headingYou can add or overwrite elements in the object just like you would with Object.assign.
javascript
const foo = { id: 1, name: 'Etch' };
const bar = {
...foo,
name: 'Etch Software',
services: 'Software development',
};
// bar = {
// id: 1,
// name: 'Etch Software',
// services: 'Software development',
// };
Object destructuring
Permalink to "Object destructuring" headingYou can combine the rest spread operator with object destructuring to pluck variables you want out of an object and do something with the rest of them.
javascript
// A button component that accepts children
// and passes the rest of the props through.
function UselessButton({ children, ...rest }) {
return (
<button {...rest}>
{children}
</button>
);
}