-2

i am tyrinig to clone an object, do you know if exist a better solution of this one?

this.objClone = JSON.parse(JSON.stringify(this.obj));

I am using redux and i have this error:

ERROR TypeError: Cannot assign to read only property 'value' of object '[object Object]'

1

3 Answers 3

3

You can use the spread operator for that.

let original = {value: 'test'};
let copy = {...original};
copy.value = 'new test';

console.log(original.value)// -> 'test'
console.log(copy.value) // -> 'new test'
Sign up to request clarification or add additional context in comments.

2 Comments

i am using redux and when i use your proposal i have this errror ERROR TypeError: Cannot assign to read only property 'value' of object '[object Object]'
This is a shallow cloning. If you have anything deeper than 1 level, it will be the same object. For example, this code will print 5 var x ={ a: { b: 1 } }; var y = {...x}; x.a.b=5; console.log(y.a.b);
2

Try using

this.objClone = Object.assign({}, this.obj);

you can also use use lodash :

lodash is recommended for lot of objects / array manipulations

possible copy of Cloning objects TypeScript , What's alternative to angular.copy in Angular or What is the most efficient way to deep clone an object in JavaScript?

1 Comment

Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value.
0

you can use Lodash's cloneDeep but JSON clone have better performance

4 Comments

Please don't refer to an entire library for something that can be done in Native Typescript.
@Nicolas Well you know these days webpack knows how to include only the imported function and not an entire library.
I know, but if OP's did not specified the use of such library, I don't see the point of suggesting it. You answer is not wrong, far from it. It just does not seams relevent to the current context.
@Nicolas Idk the use of JSON clone kind of implies that he wants to deep clone

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.