In this article, we will cover how we can update all values in an object in JavaScript using two approaches – once using object mutation which is modifying the values inside of the original object itself and another without mutation by creating a new object with the new values that we require.
Update All Values In An Object In JavaScript
First, let’s create our object and initialize it with some key-value pairs –
const object = {
key1: "value1",
key2: "value2",
key3: "value3"
};
Update All Values In An Object Using Object Mutation
1. Using forEach
In order to update all the values inside of an object by modifying the original object itself, we will have to create an array with object keys using `Object.keys()` and the iterate over each key inside of the object and change its value. So, Let’s create our array of object keys –
const objectKeys = Object.keys(object);
Then we are going to iterate over the array of keys using the `forEach()` method or we can use a regular for loop as well. For each key value we are going to set it to an empty string `” “`
const object = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const objectKeys = Object.keys(object);
objectKeys.forEach((key) => {
object[key] = " ";
});
Now, if we print our object in the console, we will see that all the key values are set to empty strings –
console.log(object);
Let’s go through the code step by step:
const object = { key1: "value1", key2: "value2", key3: "value3" };
: This line defines an object calledobject
with three key-value pairs. The keys arekey1
,key2
, andkey3
, and their corresponding values are"value1"
,"value2"
, and"value3"
respectively.objectKeys.forEach((key) => { object[key] = " "; });
: This block of code uses theforEach()
method to iterate over the keys of theobject
. Let’s break it down:objectKeys
: To make the code work correctly, we should defineobjectKeys
as an array containing the keys of theobject
. We can do this using –const objectKeys = Object.keys(object);
forEach((key) => { object[key] = " "; })
: TheforEach()
method is called on theobjectKeys
array. It takes a callback function as an argument. This callback function is invoked for each element in the array, and the current element (in this case, a key from theobjectKeys
array) is passed as an argument to the function. The purpose of this loop is to iterate over each key in theobjectKeys
array and update the corresponding value in theobject
to an empty string" "
.object[key] = " ";
: In each iteration of theforEach()
loop, the currentkey
is used as the property name to access the corresponding value in theobject
. Then, the value is set to an empty string" "
, effectively replacing the original values of"value1"
,"value2"
, and"value3"
with empty strings.
2. Using for…of
In this example, we have an object called object
, and we want to set all the values associated with its keys to an empty string " "
. Here’s the code using a for...of
loop:
const object = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const objectKeys = Object.keys(object);
for (const key of objectKeys) {
object[key] = " ";
}
Now, let’s explain the code step by step:
const objectKeys = Object.keys(object);
: This line uses theObject.keys()
method to extract all the keys from theobject
and store them in an array calledobjectKeys
. TheObject.keys()
method returns an array containing the names of all the enumerable properties (keys) of the given object.for (const key of objectKeys) {
: This line starts afor...of
loop. Thefor...of
loop is a modern iteration construct in JavaScript introduced in ECMAScript 6 (ES6). It allows you to loop over iterable objects like arrays, strings, maps, sets, etc.object[key] = " ";
: This line sets the value associated with each key in theobject
to an empty string" "
. It uses the square bracket notation to access the value corresponding to eachkey
and assigns it the value" "
.- The
for...of
loop will continue to iterate through each key inobjectKeys
, and in each iteration, the corresponding value inobject
will be set to an empty string.
Update All Values In An Object Without Object Mutation
An alternative approach to mutating the original object, is to create a new object with the same keys of the original object and assign them new values we want. We can achieve this using the `reduce()` method which takes a callback function with 2 arguments, the accumulator which is our new object, the keys which we are going to set, and an empty object `{}`
const object = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const objectKeys = Object.keys(object);
const newObject = objectKeys.reduce((accumulator, key) => {
return { ...accumulator, [key]: "" };
}, {});
Now, if we print our original object in the console, we will see that it still has the same values unchanged –
console.log(object);
Let’s check the new object created with the new values –
console.log(newObject);
Let’s break down the code step by step:
const object = { key1: "value1", key2: "value2", key3: "value3" };
: This line defines an object calledobject
with three key-value pairs. The keys arekey1
,key2
, andkey3
, and their corresponding values are"value1"
,"value2"
, and"value3"
respectively.const objectKeys = Object.keys(object);
: This line uses theObject.keys()
method to extract all the keys from theobject
and stores them in an array calledobjectKeys
. TheObject.keys()
method returns an array containing the names of all the enumerable properties (keys) of the given object.const newObject = objectKeys.reduce((accumulator, key) => { return { ...accumulator, [key]: "" }; }, {});
: This line uses thereduce()
method on theobjectKeys
array to create a new object with the same keys asobject
, but with their corresponding values set to an empty string""
.
Now, let’s explain the reduce()
method in more detail:
reduce()
: Thereduce()
method is used to reduce an array or iterable into a single value. It takes a callback function as its first argument, which is executed for each element in the array. The callback function takes two parameters: anaccumulator
and the currentvalue
. Optionally, you can provide an initial value for theaccumulator
as the second argument toreduce()
.
In this code:
- The initial value for the
accumulator
is an empty object{}
provided at the end of thereduce()
method as the second argument ({}
). This empty object will be used to build the new objectnewObject
. - The callback function
(accumulator, key) => { return { ...accumulator, [key]: "" }; }
takes two parameters:accumulator
andkey
. - In each iteration, the callback function creates a new object using the spread syntax
{ ...accumulator }
. This syntax creates a shallow copy of theaccumulator
object so that we don’t modify the originalaccumulator
object. This is important for immutability. - Then, the current
key
is used as the property name, and an empty string""
is assigned as its value using[key]: ""
. - The new object created in each iteration becomes the
accumulator
for the next iteration. - The
reduce()
method continues iterating over eachkey
in theobjectKeys
array, and the final result is an objectnewObject
with the same keys asobject
, but all the values are set to an empty string""
.
Update Values In An Object Based On A Condition
Let’s demonstrate how to update values in an object based on a condition using all three methods we discussed earlier:
- Using
Object.keys
andfor...of
loop:
const object = {
key1: 10,
key2: 20,
key3: 30
};
const objectKeys = Object.keys(object);
for (const key of objectKeys) {
if (object[key] > 15) {
object[key] = 100;
}
}
console.log(object);
- Using
Object.keys()
andforEach()
:
const object = {
key1: 10,
key2: 20,
key3: 30
};
const objectKeys = Object.keys(object);
objectKeys.forEach((key) => {
if (object[key] > 15) {
object[key] = 100;
}
});
console.log(object);
3. Using Object.keys()
and reduce()
:
const object = {
key1: 10,
key2: 20,
key3: 30
};
const updatedObject = Object.keys(object).reduce((acc, key) => {
acc[key] = object[key] > 15 ? 100 : object[key];
return acc;
}, {});
console.log(updatedObject);
In each of the above examples, we have the same initial object
with keys key1
, key2
, and key3
, each having a numeric value. We then update the values based on the condition that if the value is greater than 15, we change it to 100.
After executing any of the three methods, the result will be the same:
// Output
{
key1: 10,
key2: 100,
key3: 100
}
The values associated with key2
and key3
have been updated to 100, as they were greater than 15, while the value of key1
remains unchanged, as it was not greater than 15.
Conclusion
In this discussion, we explored different methods to update values in object in JavaScript. We had an initial object with various key-value pairs, and the goal was to modify the values in the object based on a specific condition.
We examined three main approaches for achieving this task:
- Using a for…in loop: This traditional looping method iterates over the object’s enumerable properties. It involves checking for the existence of each key and updating the values.
- Using Object.keys() and forEach(): By utilizing Object.keys(), we obtained an array of keys from the object. We then used the forEach() method to loop through the keys and update the values.
- Using Object.keys() and reduce(): We utilized Object.keys() to directly obtain an array of keys from the object. We then used the reduce() method to process each key and create a new object with updated values.
Each method achieved the same result, but they differed in their implementation and syntax. It is important to consider the specific use case and requirements when choosing the most appropriate method. Additionally, the choice between updating the existing object in place or creating a new object depends on whether you want to preserve the original object’s data or not.
Overall, updating values in an object is a common operation in JavaScript, and knowing these different methods equips developers with the flexibility to handle such scenarios efficiently.