Modifying a copy of a JavaScript object is causing the original object to change

前端 未结 5 1107
野趣味
野趣味 2020-11-22 05:06

I am copying myObj to tempMyObj

var tempMyObj = myObj;

tempMyObj.entity is an array of objects. I am

5条回答
  •  长情又很酷
    2020-11-22 05:28

    It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does.

    In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.

    Here is a simplified illustration that may help you visualize what is happening

    // [Object1]<--------- myObj
    
    var tempMyObj = myObj;
    
    // [Object1]<--------- myObj
    //         ^ 
    //         |
    //         ----------- tempMyObj
    

    As you can see after the assignment, both references are pointing to the same object.

    You need to create a copy if you need to modify one and not the other.

    // [Object1]<--------- myObj
    
    const tempMyObj = Object.assign({}, myObj);
    
    // [Object1]<--------- myObj
    // [Object2]<--------- tempMyObj
    

    Old Answer:

    Here are a couple of other ways of creating a copy of an object

    Since you are already using jQuery:

    var newObject = jQuery.extend(true, {}, myObj);
    

    With vanilla JavaScript

    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 newObject = clone(myObj);
    

    See here and here

提交回复
热议问题