1

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?

1
  • Use Object.assign to avoid object duplication. Commented Mar 18, 2020 at 8:46

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.