keep in mind...
- you can still do it the old way, but shouldn't!
- way simpler way to create objects
- can even be used to merge objects! (shallow)
ES6 makes working with objects way easier than before.
syntax Whereas we used to write out object by adding each key and value inside the object,
const obj = { id: id, color: color, name: name }
const id = 3, color = 'red', name = 'pete'; const obj = { id: id, color: color, name: name }; console.log(obj);
Now we can just write a shorthand version:
const obj = { id, color, name };
const id = 3, color = 'red', name = 'pete'; const obj = { id, color, name }; console.log(obj);
merge with spread For simple objects you can easily merge them in ES6 by using the spread operator. Beware: this does not work for complex objects. See this David Walsh article on deep merge for that.
const colorObj = { 'hue':'purple', 'sat': 'dark', 'lum': 'bright' }; const nameObj = { 'name ': 'happy'}; const obj = { ...colorObj, ...nameObj }; console.log(obj);