let obj = {}; obj.name = "dhoni"; obj.year= 2020; obj.speak = function(){ return "My Name is "+this.name+" and this is year "+this.year;}
Here you can see the name, year and speak properties. In JS methods are also properties with type function. Lets begin
Before we start, lets check out a typical object initialization in JS.
let newObj = obj; obj.year= 2021; console.log(newObj.year) // 2021 console.log(newObj.speak()) // My Name is dhoni and this is year 2021
You can create a shallow copy i.e. a top level properties copy, using Objects.assign{} method.
let copyObject = Object.assign({} ,newObj); copyObject.name = "kohli"; console.log(copyObject.speak()); // My Name is kohli and this is year 2021 console.log(newObject.speak()); // My Name is dhoni and this is year 2021
let deepCopyObj = JSON.parse(JSON.stringify(obj)); console.log(deepCopyObj); // {name: 'dhoni', year: 2019 }
Object.create() function has additional flexibility that you can choose what will be prototype of your new object.
let createObj = Object.create(obj); console.log(createObj); //{} createObj.name = "PK" console.log(createObj.speak()); // My Name is PK and this is year 2021
if you just need to copy only properties that are not functions- there is an efficient method. We are moving away from Object constructor here and using another global object in JS- JSON
let person = {name: "Roger" , age: 30) let entries = Object.entries(person); console.log(entries); // [ [ 'name', 'Roger' ], [ 'age', 30 ] ]
this function picks only keys (or property labels) of objects and returns an array.
let keys = Object.keys(person); console.log(keys); // [ 'name', 'age' ]
Object.entries() method returns an array of key-value pairs of object's enumerable properties.
let values = Object.values(person); console.log(values); // [ 'roger', 30 ]
This function picks only values of objects and returns an array.
let frozenObject = Object.freeze(person); frozenObject.name = "tendulkar"; console.log(frozenObject); // { name: 'Roger'. age: 30 }
This function freezes the object for any further changes (key or values). It may throw any error (unless you are in strict mode) but there will be no effect of value change on your object.
Next: 10 Best and Useful Chrome Extensions for Frontend Web Developer