6

Fairly straight forward question but Googling hasn't turned up anything as yet.

How do I copy/clone/duplicate an instance of an object in Coffeescript? I could always just create a clone() method which returns a new instance with copied values, but that seems like an error-prone way to go about it.

Does CoffeeScript offer a simpler solution?

Larry Battle
  • 9,008
  • 4
  • 41
  • 55
Chris Nolet
  • 8,714
  • 7
  • 67
  • 92

3 Answers3

8

This might work.

clone = (obj) ->
  return obj  if obj is null or typeof (obj) isnt "object"
  temp = new obj.constructor()
  for key of obj
    temp[key] = clone(obj[key])
  temp

Adopted from : What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Larry Battle
  • 9,008
  • 4
  • 41
  • 55
  • It should be `new obj.constructor()`. Otherwise you'll get a "Cannot convert 'temp' to object." – dennis Aug 17 '13 at 22:37
7

Thanks to Larry Battle for the hint:

John Resig's solution of using jQuery.extend works brilliantly!

// Shallow copy
newObject = $.extend({}, oldObject);

// Deep copy
newObject = $.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

Chris Nolet
  • 8,714
  • 7
  • 67
  • 92
  • When I do this, changing a property in the new object ends up changing in the old one, so how is this a "copy" ? – Stephen York Oct 17 '14 at 06:54
  • Hmm, that doesn't sound right :) Are you editing primitive properties or complex properties? You may need to use the deep copy if you're editing nested properties. Here's John Resig's original answer for JavaScript: http://stackoverflow.com/a/122704/746890 (John was the creator of jQuery). – Chris Nolet Oct 17 '14 at 07:06
  • 1
    I think I sorted it. I think it was KnockoutJS wrapping my JS object as a KO VM. – Stephen York Oct 19 '14 at 22:02
2

From The CoffeeScript Cookbook:

http://coffeescriptcookbook.com/chapters/classes_and_objects/cloning

Underscore.js also has a shallow clone function:

http://underscorejs.org/#clone

Dave Stern
  • 511
  • 2
  • 7
  • 13