Borislav Hadzhiev
Sun Nov 07 2021·2 min read
Photo by Kevin Laminto
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
.
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.
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.
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.
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.
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
.
forEach
in this scenario, because I find it more direct. If you don't want to mutate the original object, use the reduce
method.