3

I'd hope to find an example code to do a deep copying of objects in ECMAScript5.

The copying should be able to clone

  • Nested objects

  • Nested arrays

  • Nested objects in arrays (clone each array item individually)

Note: jQuery.extend() does not seem to handle case 3). Also, I'd hope to do this in clean ECMAScript. Quick googling did not bring up any worthy implementations.

Paul Sweatte
  • 22,871
  • 7
  • 116
  • 244
Mikko Ohtamaa
  • 69,174
  • 40
  • 208
  • 346

3 Answers3

1

if you want a one-liner (removes object refs by iterating through referenced objects to retrieve primitives, concats one large string, then parses the string into a new object with it's own primitive leaf nodes)

JSON.parse(JSON.stringify(obj))

or if you need to perform many copies

function deepCopy(o) {
    var copy = o,k;

    if (o && typeof o === 'object') {
        copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {};
        for (k in o) {
            copy[k] = deepCopy(o[k]);
        }
    }

    return copy;
}

performance comparison

neaumusic
  • 8,193
  • 7
  • 41
  • 65
1

I finally settled to jQuery.extend() as I couldn't find other good implementations

http://api.jquery.com/jQuery.extend/

Mikko Ohtamaa
  • 69,174
  • 40
  • 208
  • 346
0

Use an emulation of the toSource method to copy the object:

    <script type="text/javascript">
    Object.prototype.getSource = function() {
      var output = [], temp;
      for (var i in this) {
          if (this.hasOwnProperty(i)) {
              temp = i + ":";
              switch (typeof this[i]) {
                  case "object" :
                      temp += this[i].getSource();
                      break;
                  case "string" :
                      temp += "\"" + this[i] + "\"";    // add in some code to escape quotes
                      break;
                  default :
                      temp += this[i];
              }
              output.push(temp);
          }
      }
      return "{" + output.join() + "}";
      }
      var baz = {"alpha":{"beta":{"charlie": ["delta","epsilon",{"omega":"zeta"}]}}};
      !!Object.prototype.toSource ? alert((baz).toSource() ) : alert((baz).getSource() );
    </script>
Community
  • 1
  • 1
Paul Sweatte
  • 22,871
  • 7
  • 116
  • 244