Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...