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
1const person = {
2 firstName: 'John',
3 lastName: 'Doe'
4};
5
6
7// using spread ...
8let p1 = {
9 ...person
10};
11
12// using Object.assign() method
13let p2 = Object.assign({}, person);
14
15// using JSON
16let p3 = JSON.parse(JSON.stringify(person));
1The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
2const target = { a: 1, b: 2 };
3const source = { b: 4, c: 5 };
4
5const returnedTarget = Object.assign(target, source);
6
7console.log(target);
8// expected output: Object { a: 1, b: 4, c: 5 }
9
10console.log(returnedTarget);
11// expected output: Object { a: 1, b: 4, c: 5 }