Borislav Hadzhiev
Reading timeยท2 min
Photo from Unsplash
To set all properties of an object to false
:
Object.keys()
method to get an array of the object's keys.forEach()
method to iterate over the array.false
.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.
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.
To set all properties of an object to false
:
Object.keys()
method to get an array of the object's keys.reduce()
method to iterate over the array.false
to the accumulated object.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
.