Overview
In Javascript, we can use the built-in Object constructor creates an object wrapper. There are a bunch of methods that work with this constructor, such as Object.assign(). This is a short introduction about the Object constructor. Let's walkthrough some of the common methods in detail.
Object.assign()
Object.assign() copies other objects values to a new target object.
let obj1 = {a: 1, b: 2, c: 3};
let obj2 = {d: 4, e: 4, c: 6};
let newObj = Object.assign({}, obj1, obj2);
console.log(newObj);
{ a: 1, b: 2, c: 6, d: 4, e: 5 }
Notice that the c: 3 from obj1 did not copy to newObj, that because obj2 has the same key c: 6 and is overwritten the value on obj1. Also without the empty curly bracket, the first argument will be altered and merge with obj2.(known as destructive)
let obj1 = {a: 1, b: 2, c: 3};
let obj2 = {d: 4, e: 4, c: 6};
let newObj = Object.assign(obj1, obj2);
console.log(newObj);
{ a: 1, b: 2, c: 6, d: 4, e: 5 }
console.log(Obj1);
{ a: 1, b: 2, c: 6, d: 4, e: 5 }
console.log(Obj2);
{d: 4, e: 4, c: 6}
Object.values()
The Object.values() will return an array contains all the values from the object that is being parsed.
let testObj = {name: 'Vegas', age: 25, hairColor: 'dark'};
Object.values(testObj);
console.log(valueObj);
Array ["Vegas", 25, "dark"]
Object.keys()
Similar to Object.values, Object.keys will return an array containing all keys attributes, like so:
let testObj = {name: 'Vegas', age: 25, hairColor: 'dark'};
Object.keys(testObj);
console.log(valueObj);
Array ["name", "age", "hairColor"]
Object.entries()
Object.entries returns both key and values like so:
let testObj = {name: 'Vegas', age: 25, hairColor: 'dark'};
valueObj = Object.entries(testObj);
console.log(valueObj);
Array [Array ["name", "Vegas"], Array ["age", 25], Array ["hairColor", "dark"]]
Conclusion
Object constructor and its methods are very helpful when we work on datasets such as json format data.
To learn more, all other Object constructor methods can be found here:
Mozilla.org
Top comments (2)
Nice Object tips but there are a few typos. In your first example with Object.assign(), the new object will contain: { a: 1, b: 2, c: 6, d: 4, e: 4 }. If you omit the empty object parameter in Object.assign(), newObj will again contain: { a: 1, b: 2, c: 6, d: 4, e: 4 }. obj1 will be merged with obj2 to also contain { a: 1, b: 2, c: 6, d: 4, e: 4 }, and obj2 will not be altered. And in your last examples, don't forget to initialize/assign a value to 'valueObj' before using it.
thank you for your comments.