Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 256
runtimeZero Avatar asked Dec 17 '14 15:12

runtimeZero


People also ask

How do you clear an object in JavaScript?

The only way to fully remove the properties of an object in JavaScript is by using delete operator. If the property which you're trying to delete doesn't exist, delete won't have any effect and can return true.

How do you reset an objects value?

reset( obj ) resets the internal state and input properties of the object obj . If obj writes or reads a file, reset resets the object to the beginning of the file. If obj changes properties, reset resets the properties to their initial default values.

How do you remove a property from an object?

In JavaScript, there are 2 common ways to remove properties from an object. The first mutable approach is to use the delete object. property operator. The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...


1 Answers

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.

like image 115
dfsq Avatar answered Sep 30 '22 18:09

dfsq