Set all Object Properties to False in JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Set all Object Properties to False in JavaScript #

To set all properties of an object to false:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use the forEach() method to iterate over the array.
  3. Set each object key to false.
index.js
const obj = { bobby: true, hadz: false, com: true, }; Object.keys(obj).forEach(key => { obj[key] = false; }); // ๐Ÿ‘‡๏ธ { bobby: false, hadz: false, com: false } console.log(obj);

The Object.keys method returns an array of the object's keys.

index.js
const obj = { bobby: true, hadz: false, com: true, }; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(Object.keys(obj));

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

On each iteration, we set the value of the current property to false.

The forEach() method returns undefined, so we have to perform some kind of mutation to persist the state.

After the last iteration, all of the object's properties are 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:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Use the reduce() method to iterate over the array.
  3. Set each key with a value of false to the accumulated object.
index.js
const obj = { bobby: true, hadz: false, com: true, }; const newObj = Object.keys(obj).reduce((accumulator, key) => { return {...accumulator, [key]: false}; }, {}); // ๐Ÿ‘‡๏ธ { bobby: false, hadz: false, com: false } console.log(newObj);

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

We initialized the accumulator variable to an empty object because that's what we passed as the second argument to the reduce() method.

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 a new object where all properties are set to the value of false.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev