user16891328 user16891328 - 27 days ago 6
Node.js Question

Assigning javascript object to new object as copy

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.

Answer

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

Comments