T.v.A.
T.v.A.

Reputation: 49

How to duplicate object in JS where duplicate changes if you change original

I am making a planner/calendar website that is going to have a repeat function.

var chain = _.chain(state.items).filter({'id': 1}).head().value();
console.log(chain);

Here i filter one object, how do i duplicate chain that when i change the original the duplicate also changes and the other way around?

Upvotes: 1

Views: 100

Answers (1)

Rijosh
Rijosh

Reputation: 1544

Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value. This is why the original value changing when you're changing the duplicate.

This can be solved by using JSON.parse() and JSON.stringify()

Create a new function in the methods section

cloneObject:function(obj){
  return JSON.parse(JSON.stringify(obj));
}

Now you can call this method to make a copy of any object, like

var items = this.cloneObject(state.items); // this will create a clone of the object
var chain = _.chain(items).filter({'id': 1}).head().value();

Here the filter won't effect the state.items since we made a clone of this data.

If you're already using lodash JS library, you can use the cloneDeep() method to make the copy

Eg:

var items = _.cloneDeep(state.items);
var chain = _.chain(items).filter({'id': 1}).head().value();
console.log(chain);

Upvotes: 1

Related Questions