Javascript: An introduction to Object constructor.
Yong Liang
Posted on March 22, 2019
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
Posted on March 22, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024