Set all Values in an Object to Null using JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

Set all Values in an Object to Null #

To set all values in an object to null, pass the object to the Object.keys() method to get an array of the object's keys and use the forEach() method to iterate over the array, setting each value to null. After the last iteration, the object will contain only null values.

index.js
const obj = { name: 'Tom', age: 30, country: 'Chile', }; Object.keys(obj).forEach(key => { obj[key] = null; }); // ๐Ÿ‘‡๏ธ {name: null, age: null, country: null} console.log(obj);

We used the Object.keys method to get an array of the object's keys.

index.js
const obj = { name: 'Tom', age: 30, country: 'Chile', }; // ๐Ÿ‘‡๏ธ ['name', 'age', 'country'] console.log(Object.keys(obj));

The next step is to use the Array.forEach method to iterate over the array.

The function we passed to the forEach method gets called with each element in the array.

On each iteration, we set the value of the current key of null.

After the last iteration, all of the values in the object will be set to null.

An alternative approach is to not mutate the object, but create a new object using the Array.reduce method.

Set all Values in an Object to Null using reduce() #

To set all values in an object to null, pass the object to the Object.keys() method to get an array of the object's keys and use the reduce() method to iterate over the array. On each iteration, extend the accumulator object, setting the key to a value of null and returning the result.

index.js
const obj = { name: 'Tom', age: 30, country: 'Chile', }; const newObj = Object.keys(obj).reduce((accumulator, key) => { return {...accumulator, [key]: null}; }, {}); // ๐Ÿ‘‡๏ธ {name: null, age: null, country: null} console.log(newObj);

The function we passed to the reduce method gets called for each element in the keys array.

We set the initial value for the accumulator variable to an empty object.

On each iteration, we use the spread syntax (...) to unpack the key-value pairs of the accumulated object into a new object, setting the current property to null.

It's a matter of personal preference which approach you choose. I prefer using the forEach in this scenario, because I find it more direct. If you don't want to mutate the original object, use the reduce method.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee