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