Search code examples
javascriptangularjsoopcopyextend

Use Angular to copy object properties - without values - to another object


We have tried angular.copy and angular.extend. Both of these, though, copy property values. How do we copy one object's properties, without their values, to another object?

Here is a fiddle with our attempts based on how-to-quickly-clear-a-javascript-object.

angular.module('App', []);

function Ctrl($scope) {

    function copyNotValues(obj) {
        var newObj = angular.copy(obj);
        for (prop in newObj) {
            if(newObj.hasOwnProperty(prop))
            {
                newObj[prop] = null;
            }
        };
        return newObj;
    }

    $scope.master = {
        foo: 'original foo',
        bar: 'original bar'
    };

    $scope.copy = angular.copy($scope.master);
    $scope.extend = angular.extend($scope.master);
    $scope.copyNotValues = copyNotValues($scope.master);

}

Solution

  • JavaScript doesn't have the concept of classes. It uses Prototype inheritance which means you can only create a new object by copying another object. When doing that you get the properties.

    You can get around this by creating a "master" object without property values. Something like this:

    master = {
      foo: '',
      bar: ''
    };
    

    Then you can create new 'instances' of the object with the new keyword:

    $scope.master = new master();
    $scope.master.foo = 'original foo';
    $scope.master.bar = 'original bar';
    

    When you need to create a new instance of the object, go back to the original, not your copy:

    $scope.masterCopy = new master();
    

    This is really a JavaScript issue and not an Angular specific issue. I suppose you could, theoretically, write a function to create a new instance of an object and then loop over the properties to set them all to null or empty strings.