1

I have this array of object obj.arr in javascript. I assigned it to a new object.

var obj_arr_new = obj.arr;

The problem is that when I modify obj_arr_new, obj.arr gets modified as well. I do not want that. How can I make obj_arr_new to be a copy of obj.arr and when I modify obj_arr_new, obj.arr is untouched?

I am using node.js v6. I am open to using any node.js module. Someone told me lodash can do the job. An answer using lodash would be helpful.

mklement0
  • 382,024
  • 64
  • 607
  • 775
guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • Did you do any research? There are plenty of questions about this already, and the lodash documentation is online. – 4castle Nov 05 '16 at 15:22
  • 1
    Possible duplicate of [How do I correctly clone a JavaScript object?](http://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – 4castle Nov 05 '16 at 15:24
  • I did but there were a few methods in lodash which seems to fit the bill but I don't know exactly which one. Sorry, I'm rather slow. – guagay_wk Nov 05 '16 at 15:24

2 Answers2

3

Lodash indeed has a _.cloneDeep(value) for this purpose.

var obj_arr_new = _.cloneDeep(obj.arr);

It will recursively clone "arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays" so that modifying bits of the clone doesn't affect the original, or vice versa.

Documentation

Wander Nauta
  • 18,832
  • 1
  • 45
  • 62
1

I tend to create a copy by using:

var copiedObject = JSON.parse(JSON.stringify(originalObject));

This only works for JSONable objects, but if you're dealing with strings, arrays etc then its fine, i.e not if you have functions as children of the object you're copying.

Graham Shroll
  • 281
  • 1
  • 6