1

I am having the car object in this screenshot(I couldn't find a way to pretty print it here)

enter image description here

I would like to do a function that clones one of the two elements in the factory.

I tried it like this:

public cloneFactory(modelIndex: number, factoryIndex: number): void {
    const newFactory = this.car.model[modelIndex].factory.slice(factoryIndex, factoryIndex + 1);
    this.car.model[modelIndex].factory.push(newFactory[0]);
}

I also tried it the classic way:

public cloneFactory(modelIndex: number, factoryIndex: number): void {
    const newFactory = this.car.model[modelIndex].factory[factoryIndex];
    this.car.model[modelIndex].factory.push(newFactory);
}

The issue I am having is that if I, afterwards, change one of the values in the cloned object it also changes it in the original object. I cannot understand why and how / why are the original and the clone related after one of the methods above are executed.

What is the proper way of cloning an element of the array so that it can be, later, edited without the original object to be affected as well?

1 Answer 1

3

You are not actually cloning the object. You are pushing the reference to the same object again. To clone it you can use Object.assign:

const newFactory = Object.assign({}, this.car.model[modelIndex].factory[factoryIndex]);

Here's an example of how Object.assign works compared to just assigning a reference:

var obj = { a: 1 };
var objref2 = obj; // Just assigning reference; not a clone
var clone = Object.assign({}, obj); // Actual cloned copy of `obj`
obj.a = 100;
console.log(obj.a)
-> 100 // Value changed
console.log(objref2.a)
-> 100 // Value changed
console.log(clone.a)
-> 1 // Value unchanged
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. Thank you very much!

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.