Borislav Hadzhiev
Sat Nov 20 2021·2 min read
Photo by Kalen Emsley
To update all the values in an object:
Object.keys()
method to get an array of the object's keys.forEach()
method and update each value.const obj = { country: 'Chile', city: 'Santiago', address: 'Example', }; Object.keys(obj).forEach(key => { obj[key] = ''; }); // 👇️ {country: '', city: '', address: ''} console.log(obj);
We used the Object.keys method to get an array of the object's keys.
const obj = { country: 'Chile', city: 'Santiago', address: 'Example', }; // 👇️ ['country', 'city', 'address'] console.log(Object.keys(obj));
The next step is to iterate over the array of keys using the Array.forEach method.
The function we passed to the forEach
method gets called for each element of
the array and gets passed 3 parameters:
If you need to use the index you can assign the second parameter of the callback function to a variable.
const obj = { country: 'Chile', city: 'Santiago', address: 'Example', }; Object.keys(obj).forEach((key, index) => { obj[key] = obj[key] + index; }); // 👇️ {country: 'Chile0', city: 'Santiago1', address: 'Example2'} console.log(obj);
To update all the values in an object:
Object.keys()
method to get an array of the object's keys.reduce()
method to iterate over the array.const obj = { country: 'Chile', city: 'Santiago', address: 'Example', }; const newObj = Object.keys(obj).reduce((accumulator, key) => { return {...accumulator, [key]: ''}; }, {}); console.log(newObj); // 👉️ {country: '', city: '', address: ''} // 👇️ {country: 'Chile', city: 'Santiago', address: 'Example'} console.log(obj);
We got an array of the object's keys using the Object.keys()
method.
The Array.reduce method allows us to iterate over the array.
The function we passed to the method gets called for each element (key) in the array.
We passed an initial value of an empty object for the accumulator
variable.
On each iteration, we use the spread syntax (...) to unpack the key-value pairs of the object into a new object and update the current value.
The value we return from the callback function gets passed to the reduce()
method as the next value for the accumulator.