1var student = {name: "Rahul", age: "16", hobby: "football"};
2
3//using ES6
4var studentCopy1 = Object.assign({}, student);
5//using spread syntax
6var studentCopy2 = {...student};
7//Fast cloning with data loss
8var studentCopy3 = JSON.parse(JSON.stringify(student));
1var sheep={"height":20,"name":"Melvin"};
2var clonedSheep=JSON.parse(JSON.stringify(sheep));
3
4//note: cloning like this will not work with some complex objects such as: Date(), undefined, Infinity
5// For complex objects try: lodash's cloneDeep() method or angularJS angular.copy() method
1let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
1// syntax: let <newObjectName> = {...<initialObjectName>};
2
3// example:
4const me = {
5 name: 'Jakes',
6 age: 30,
7};
8const friend = {...me};
9friend.age = 27;
10console.log(friend.age); // 27
11console.log(me.age); // 30
12
13// -----------------------------
14// BAD
15// -----------------------------
16const me = {
17 name: 'Jonas',
18 age: 30,
19};
20const friend = me;
21friend.age = 27;
22console.log(friend.age); // 27
23console.log(me.age); // 30