Update All Values In An Object In JavaScript

update all values in an object in JavaScript
update all values in object js

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);

updating values using mutation

Let’s go through the code step by step:

  1. const object = { key1: "value1", key2: "value2", key3: "value3" };: This line defines an object called object with three key-value pairs. The keys are key1, key2, and key3, and their corresponding values are "value1", "value2", and "value3" respectively.
  2. objectKeys.forEach((key) => { object[key] = " "; });: This block of code uses the forEach() method to iterate over the keys of the object. Let’s break it down:
    • objectKeys: To make the code work correctly, we should define objectKeys as an array containing the keys of the object. We can do this using – const objectKeys = Object.keys(object);
    • forEach((key) => { object[key] = " "; }): The forEach() method is called on the objectKeys 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 the objectKeys array) is passed as an argument to the function. The purpose of this loop is to iterate over each key in the objectKeys array and update the corresponding value in the object to an empty string " ".
    • object[key] = " ";: In each iteration of the forEach() loop, the current key is used as the property name to access the corresponding value in the object. 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:

  1. const objectKeys = Object.keys(object);: This line uses the Object.keys() method to extract all the keys from the object and store them in an array called objectKeys. The Object.keys() method returns an array containing the names of all the enumerable properties (keys) of the given object.
  2. for (const key of objectKeys) {: This line starts a for...of loop. The for...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.
  3. object[key] = " ";: This line sets the value associated with each key in the object to an empty string " ". It uses the square bracket notation to access the value corresponding to each key and assigns it the value " ".
  4. The for...of loop will continue to iterate through each key in objectKeys, and in each iteration, the corresponding value in object 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);

updating values without object mutation

Let’s check the new object created with the new values –

console.log(newObject);

object created with new values

Let’s break down the code step by step:

  1. const object = { key1: "value1", key2: "value2", key3: "value3" };: This line defines an object called object with three key-value pairs. The keys are key1, key2, and key3, and their corresponding values are "value1", "value2", and "value3" respectively.
  2. const objectKeys = Object.keys(object);: This line uses the Object.keys() method to extract all the keys from the object and stores them in an array called objectKeys. The Object.keys() method returns an array containing the names of all the enumerable properties (keys) of the given object.
  3. const newObject = objectKeys.reduce((accumulator, key) => { return { ...accumulator, [key]: "" }; }, {});: This line uses the reduce() method on the objectKeys array to create a new object with the same keys as object, but with their corresponding values set to an empty string "".

Now, let’s explain the reduce() method in more detail:

  • reduce(): The reduce() 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: an accumulator and the current value. Optionally, you can provide an initial value for the accumulator as the second argument to reduce().

In this code:

  • The initial value for the accumulator is an empty object {} provided at the end of the reduce() method as the second argument ({}). This empty object will be used to build the new object newObject.
  • The callback function (accumulator, key) => { return { ...accumulator, [key]: "" }; } takes two parameters: accumulator and key.
  • In each iteration, the callback function creates a new object using the spread syntax { ...accumulator }. This syntax creates a shallow copy of the accumulator object so that we don’t modify the original accumulator 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 each key in the objectKeys array, and the final result is an object newObject with the same keys as object, 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:

  1. Using Object.keys and for...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);

  1. Using Object.keys() and forEach():
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:

  1. 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.
  2. 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.
  3. 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.

Leave a Reply