js create a copy of object code example

Example 1: clone object in js

var student = {name: "Rahul", age: "16", hobby: "football"};

//using ES6
var studentCopy1 = Object.assign({}, student);
//using spread syntax
var studentCopy2 = {...student}; 
//Fast cloning with data loss
var studentCopy3 = JSON.parse(JSON.stringify(student));

Example 2: copy object javascript

var x = {myProp: "value"};
var y = Object.assign({}, x);

Example 3: copy object javascript

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

//this method actually creates a reference-free version of the object, unlike the other methods
//If you do not use Dates, functions, undefined, regExp or Infinity within your object

Example 4: copy an object with object.assign

// We want to update status property value to 'online'
const data = {
  user: 'CamperBot',
  status: 'offline',
  friends: '732,982',
};

// Object.assign takes in a target object (1st parameter) and source objects 
// (rest of the parameter list). Source object properties are mapped to the 
// target object (which is usually empty). Any matching properties are 
// overwritten by the source objects
const newObject = Object.assign({}, data, {status: 'online'})

console.log(newObject)
/* 
  {
    user: 'CamperBot',
    status: 'online',
    friends: '732,982',
  }
*/