javascript copy by value code example
Example 1: copy object javascript
const obj = {name: 'john', surname: 'smith'};
const objCopy = {...obj};
Example 2: clone javascript object
let clone = Object.assign({}, objToClone);
Example 3: copy object javascript
var x = {key: 'value'}
var y = JSON.parse(JSON.stringify(x))
Example 4: javascript clone object
var x = {myProp: "value"};
var xClone = Object.assign({}, x);
Example 5: best way to clone an object in javascript
const person = {
firstName: 'John',
lastName: 'Doe'
};
let p1 = {
...person
};
let p2 = Object.assign({}, person);
let p3 = JSON.parse(JSON.stringify(person));
Example 6: mdn object assign
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const returnedTarget = Object.assign(target, source);
console.log(target);
console.log(returnedTarget);