2

I have an object, which i search the keys and modify the values if a key match is found:

var myData = // some http.get which returns a JSON object.

Imagine myData is:

myData : {
    "suffix" : "mr",
    "fname" : "jullian",
    "lname" : "exor",
    "dobGmt" : 145754294700000
    "addressLine1" : "xxx",
    "street" : "xxx",
    "rentStartedGmt" : 145754294700000,
    "deposit" : "50.00",
    "occupation" : "math teacher",
    "profession" : {
         "careerStartedGmt": 1458755224800000,
         "careerEndGmt": 1459854224800000,
     }
}

$scope.viewData = function() {
    var objClone = _.clone(myData);
    objClone = myFactory.ProcessData(objClone);
    $scope.view = objClone;
};

$scope.viewProducts = function() {

};

MyFactory:

myModule.factory('myFactory', function() {
    return {
        ProcessData: function(data) {
            var tmp = data;

            function findGmt(tmp) {
                for (var key in tmp) {
                    var v = tmp[key];
                        if (key.indexOf("Gmt") !== -1) {
                            tmp[key] = tmp[key].format('DD-MM-YY HH:mm');    
                        }    
                    }
                }

            findGmt(tmp);

            return tmp;
        }
    }
});

User can click on viewData button which calls $scope.viewData which displays the formatted JSON in a modal on the same page. User then clicks on viewProducts which calls $scope.viewProducts which displays a list of products in a modal on the same page.

However, after clicking viewProducts, if i go back to click viewData again, on debugging, i can see var objClone is already formatted, rather than taking a new clone of _.clone(myData);

Have a missed how to clone/not modifiy original objects?

Val
  • 17,336
  • 23
  • 95
  • 144
Oam Psy
  • 8,555
  • 32
  • 93
  • 157
  • @evolutionxbox duplicate in context, not helpful when the op asked for a totally different language. – Val Apr 19 '16 at 11:10
  • @Val - my bad - removed – evolutionxbox Apr 19 '16 at 11:11
  • 2
    I personal would try this link, http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object (which is `.extend` but not sure about if reference is lost or not as you have asked) – Val Apr 19 '16 at 11:13

2 Answers2

2

Usually, clone functions (that can now be replaced by the standard Object.assign) only copy the provided object properties into a new object. They do not recursively clone the values of the object. That means that the content of your profession property, for example, is the same object for the cloned and the original: myData.profession === objClone.profession is true.

What you are looking for is a deep clone function.

Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
1

You have to use var copiedObj = angular.copy(myObj). It will create copy of the myObj but changing myObj won't change anything in copiedObj.

Atul Chaudhary
  • 3,698
  • 1
  • 31
  • 51