Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active March 20, 2020 10:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save miguelmota/300445a06a342e47a335 to your computer and use it in GitHub Desktop.
Save miguelmota/300445a06a342e47a335 to your computer and use it in GitHub Desktop.
Deep clone copy array with lodash (underscore)
var array = [{},{},{}];
var copy = _.map(array, _.clone);
@hongbo-miao
Copy link

thanks! works perfect!

@jhlosin
Copy link

jhlosin commented Feb 16, 2017

great. Thank you.

@huydoansg
Copy link

Thanks. It works perfect!

@Zaynex
Copy link

Zaynex commented Dec 13, 2017

var array = [{},{},{}];
var copy = array.slice();

It's easy and not change array

@liester
Copy link

liester commented Jan 9, 2018

Lodash _.clone only creates a shallow copy, same with Array.prototype.slice. If you want a deep copy I believe you will need one of the following:
1). JSON.parse(JSON.stringify(obj)) - doesn't handle functions
2). Lodash's _.cloneDeep (or and other similar library)
3). Custom clone method.

@lebed
Copy link

lebed commented Aug 17, 2018

Also you can use the spread operator or Object.assign, something like that:
var array = [{id: 0}];
array.map(obj => ({...obj, id: 5}));

@felix9ia
Copy link

felix9ia commented Nov 2, 2018

@Zaynex It is a Shallow Clone, not work for Reference type

Copy link

ghost commented Mar 11, 2019

var array = [{},{},{}];
var copy = array.slice();

It's easy and not change array

This won't work.

@turkoz
Copy link

turkoz commented May 15, 2019

Beautiful touch!..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment