-4

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]'

Gelso77
  • 1,763
  • 6
  • 30
  • 47
  • if you need a deep clone. https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – dismedia Dec 02 '19 at 13:44

3 Answers3

1

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?

Benjamin Barbé
  • 494
  • 6
  • 18
  • 2
    Object.assign() copies property values. If the source value is a reference to an object, it only copies that reference value. – Saurabh Yadav Dec 02 '19 at 13:44
0

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

Ron
  • 844
  • 7
  • 8
  • 1
    Please don't refer to an entire library for something that can be done in Native Typescript. – Nicolas Dec 02 '19 at 13:44
  • @Nicolas Well you know these days webpack knows how to include only the imported function and not an entire library. – Ron Dec 02 '19 at 13:47
  • 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 Dec 02 '19 at 13:49
  • 1
    @Nicolas Idk the use of JSON clone kind of implies that he wants to deep clone – Ron Dec 02 '19 at 13:51
0

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'
Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • 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]' – Gelso77 Dec 02 '19 at 14:43
  • 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); – Asaf Mar 30 '23 at 17:05