1
Order.prototype.selectItem = function(newItem) { ...

newItem is the object I want to copy and then modify the copy without modifying the original newItem.

var newSelectedItem = newItem;
newSelectedItem.orderIndex = this.selectedItems.length + 1;

Changing the orderIndex of the copy will also change the original newItem.

Question: How do I copy and then modify the copy without modifying the original newItem.

Thanks!

Fostah
  • 2,947
  • 4
  • 56
  • 78

3 Answers3

2

Create a new object

var newSelectedItem = {};

And copy all properties from the old object into the new one

for(var prop in newItem){
    if(newItem.hasOwnProperty(prop)){
        newSelectedItem[prop] = newItem[prop];
    }
}

Note that this solution only works for plain objects that are flat. If "newItem" is an instance of some prototype you cannot just create the new object with {} and if properties can contain mutable arrays or objects then you also need to do a recursive deep copy.

For more examples, the dojo toolkit has some functions (mixin and clone) for doing this kind of thing: http://trac.dojotoolkit.org/browser/dojo/dojo/trunk/_base/lang.js

hugomg
  • 68,213
  • 24
  • 160
  • 246
1

If you're using jQuery (which I'd suggest), you can clone objects per this post: What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
D. Patrick
  • 2,894
  • 26
  • 37
  • By the way, please note the person who answered that question. :) – D. Patrick Jan 25 '12 at 19:03
  • This was perfect! Answers from John Resig are always nice! Below is what I ended up using: // Deep copy var newObject = jQuery.extend(true, {}, oldObject); – Fostah Jan 25 '12 at 19:08
0

You don't necessarily need to clone the object. If all you want to do is have an object you can set properties on without altering the original, the so-called "Boodman/Crockford delegation" is far more efficient. Wishing I had published that when I first used it :) See also dojo.delegate

peller
  • 4,435
  • 19
  • 21