js copy object to another code example

Example 1: make copy of object javascript

var x = {key: 'value'}
var y = JSON.parse(JSON.stringify(x))

//If you do not use Dates, functions, undefined, regExp or Infinity within your object

Example 2: best way to clone an object in javascript

const person = {
    firstName: 'John',
    lastName: 'Doe'
};


// using spread ...
let p1 = {
    ...person
};

// using  Object.assign() method
let p2 = Object.assign({}, person);

// using JSON
let p3 = JSON.parse(JSON.stringify(person));