Nodejs: how to clone an object

后端 未结 12 2066
情书的邮戳
情书的邮戳 2020-12-04 18:32

If I clone an array, I use cloneArr = arr.slice()

I want to know how to clone an object in nodejs.

12条回答
  •  佛祖请我去吃肉
    2020-12-04 19:17

    There is no native method for cloning objects. Underscore implements _.clone which is a shallow clone.

    _.clone = function(obj) {
      return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
    };
    

    It either slices it or extends it.

    Here's _.extend

    // extend the obj (first parameter)
    _.extend = function(obj) {
      // for each other parameter
      each(slice.call(arguments, 1), function(source) {
        // loop through all properties of the other objects
        for (var prop in source) {
          // if the property is not undefined then add it to the object.
          if (source[prop] !== void 0) obj[prop] = source[prop];
        }
      });
      // return the object (first parameter)
      return obj;
    };
    

    Extend simply iterates through all the items and creates a new object with the items in it.

    You can roll out your own naive implementation if you want

    function clone(o) {
      var ret = {};
      Object.keys(o).forEach(function (val) {
        ret[val] = o[val];
      });
      return ret;
    }
    

    There are good reasons to avoid deep cloning because closures cannot be cloned.

    I've personally asked a question about deep cloning objects before and the conclusion I came to is that you just don't do it.

    My recommendation is use underscore and it's _.clone method for shallow clones

提交回复
热议问题