Set all Object Properties to False in JavaScript

avatar

Borislav Hadzhiev

Sun Nov 07 20212 min read

banner

Photo by Kevin Laminto

Set all Object Properties to False #

To set all properties of an Object to false, 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 and set each of the object's properties to a value of false.

index.js
const obj = { one: true, two: false, three: true, }; Object.keys(obj).forEach(key => { obj[key] = false; }); // ๐Ÿ‘‡๏ธ {one: false, two: false, three: false} console.log(obj);

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

index.js
const obj = { one: true, two: false, three: true, }; // ๐Ÿ‘‡๏ธ ['one', 'two', 'three'] 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 for the property to false.

After the last iteration, all of the object's properties will be set to false.

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

Set all Object Properties to False using reduce() #

To set all properties of an Object to false, 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 property to false and returning the result.

index.js
const obj = { one: true, two: false, three: true, }; const newObj = Object.keys(obj).reduce((accumulator, key) => { return {...accumulator, [key]: false}; }, {}); // ๐Ÿ‘‡๏ธ {one: false, two: false, three: false} 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 false.

The value we return from the callback function gets passed as the accumulator for the next iteration.

After the last iteration, we get an object where all properties are set to the value of false.

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