Skip to content
Advertisement

Best way to reset all values in an Javascript object

My javascript object looks something like:

$scope.display = {
  current: {
       key1: 'value1',
       key2: ['a', 'b'],
       key3: 'value2'
    }
}

Upon some events in my code, I would like to reset these values to undefined like below:

$scope.display = {
  current: {
       key1: undefined,
       key2: [],
       key3: undefined
    }
}

I use libraries like lodash, however i don’t see any function that would perform this. I know how to do this manually, but I was wondering if there is a “Best practices” way of performing this task.

Advertisement

Answer

I would create a helper function returning object structure:

function getDisplayObject() {
    return {
        current: {
            key1: undefined, // or you can omit undefined keys
            key2: [],
            key3: undefined
        }
    };
}

$scope.display = getDisplayObject();

So later when you need to reset data you would execute $scope.display = getDisplayObject(); again.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement