Last active
March 20, 2020 10:10
-
-
Save miguelmota/300445a06a342e47a335 to your computer and use it in GitHub Desktop.
Deep clone copy array with lodash (underscore)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var array = [{},{},{}]; | |
var copy = _.map(array, _.clone); |
var array = [{},{},{}];
var copy = array.slice();
It's easy and not change array
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.
Also you can use the spread operator or Object.assign, something like that:
var array = [{id: 0}];
array.map(obj => ({...obj, id: 5}));
@Zaynex It is a Shallow Clone, not work for Reference type
var array = [{},{},{}]; var copy = array.slice();
It's easy and not change
array
This won't work.
Beautiful touch!..
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. It works perfect!