Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a deep copy of Object with get and set operators in JS

Tags:

javascript

I hope you'll help me.

I want to make a deep copy of this object User.

function clone(obj) {
    if (null == obj || "object" != typeof obj)
        return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr))
            copy[attr] = obj[attr];
    }
  return copy;
}

var User = {
    _firstName: 'robert',

    get firstName() {
        return this._firstName;
    },
    set firstName(val) {
        this._firstName = val;
    },

    affFirstName: function() {
        console.log(this._firstName);
    },
};

console.log(User);
var User2 = clone(User);    
console.log(User2);

This function clone doesn't work (see fiddle for example)

This copy creates new variable with the name of get and set.

Set and get Operators are not copied.

But the function affFirstName() is well copied.

Do you have a solution ?

like image 243
user2550884 Avatar asked Jan 13 '23 00:01

user2550884


2 Answers

In ES5, you can use Object.getOwnPropertyDescriptor to get a copy of the getters and setters that may exist on an object.

You can then pass those descriptors to Object.defineProperty to recreate them on a new object.

Note that if those getters or setters rely on lexically scoped variables the new clone will share those variables with the original object. The new object will not get its own copy of those variables.

like image 146
Alnitak Avatar answered Jan 22 '23 06:01

Alnitak


function clone(obj) {
  if (null == obj || "object" != typeof obj)
    return obj;
  var copy = obj.constructor();
  for (var attr in obj) {
    if (obj.hasOwnProperty(attr)) {
      if (Object.getOwnPropertyDescriptor(obj, attr).value instanceof Object) {
        copy[attr] = clone(obj[attr]);
      }
      else {
        Object.defineProperty(copy, attr, Object.getOwnPropertyDescriptor(obj,attr));
      }
    }
  }
  return copy;
}

The corrected clone function to make a deep copy with operators get and set.

like image 39
user2550884 Avatar answered Jan 22 '23 05:01

user2550884