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));
1const target = { a: 1, b: 2 };
2const source = { b: 4, c: 5 };
3
4const returnedTarget = Object.assign(target, source);
5
6console.log(target);
7// expected output: Object { a: 1, b: 4, c: 5 }
8
9console.log(returnedTarget);
10// expected output: Object { a: 1, b: 4, c: 5 }
11
1var x = {myProp: "value"};
2var xClone = Object.assign({}, x);
3
4//Obs: nested objects are still copied as reference.
1const first = {'name': 'alka', 'age': 21}
2const another = Object.assign({}, first);
1let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
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));