Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you clone an array of objects using underscore?

#!/usr/bin/env node var _ = require('underscore'); var a = [{f: 1}, {f:5}, {f:10}]; var b = _.clone(a); b[1].f = 55; console.log(JSON.stringify(a)); 

This results in:

[{"f":1},{"f":55},{"f":10}] 

Clone does not appear to be working! So I RTFM, and see this:

http://underscorejs.org/#clone

Create a shallow-copied clone of the object. Any nested objects or arrays will be copied by reference, not duplicated.

So _.clone is pretty useless. Is there a way to actually copy the array of objects?

like image 876
Jess Avatar asked Jan 08 '14 17:01

Jess


People also ask

What is deep cloning in JavaScript?

A deep copy is a copy of all elements of the original object. Changes made to the original object will not be reflected in the copy. In this article, you will create deep copies of objects using the Lodash library.

What is clone in Lodash?

Sep 20, 2019. Lodash's clone() function is a powerful utility for shallow cloning generic objects. The Object. assign() function or the spread operator are the canonical methods for shallow copying a POJO.

How do you make a deep copy in JavaScript?

Copy an Object With Object. assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.


1 Answers

Well, there is a trick! If clone does not "clone" nested objects, you can force it to by explicitly cloning each object inside a map call! Like this:

#!/usr/bin/env node var _ = require('underscore'); var a = [{f: 1}, {f:5}, {f:10}]; var b = _.map(a, _.clone);       // <---- b[1].f = 55; console.log(JSON.stringify(a)); 

Prints:

[{"f":1},{"f":5},{"f":10}] 

Yay! a is unchanged! I can now edit b to my liking!

like image 153
Jess Avatar answered Sep 28 '22 03:09

Jess