[4 Best Methods] To Update Keys With A New Value In JavaScript

So, you want to know how to update keys with a new value in JavaScript? Well, luckily for you, today we are going to break down the four most common ways to do so!

A key in JavaScript is an important aspect of any dictionary, array, and tuple and it’s equally as important to learn how to update them. Keys are especially important in dictionaries and other data structures that use key-value pairs that correspond to different titles and values.

Updating keys in JavaScript is quite simple since JavaScript is a loosely typed programming language and allows duck typing. However, because of that, it has room for errors and mistakes which can result in issues. Keys can also be defined within separate objects which allows for better control and manipulation of the variables within the object. As we will explore a bit later on.

So let’s skip the boring stuff and lets jump right into the best ways to update keys with a new value in JavaScript:

Method 1: Update Keys Individually

let obj1 = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}
   
// You can simply update the single key value to another value using [] parenthesis
obj1['key1'] = "updated value1";
console.log(obj1)

Result:

[Running] node "g:\article\tempCodeRunnerFile.js"
{ key1: 'updated value1', key2: 'value2', key3: 'value3' }
 
[Done] exited with code=0 in 0.127 seconds

The aforementioned block of code represents updating a single key value within an object, you can update whatever value you want by simply changing the key name within the obj1[“key”] call.

This is the easiest way to update a key-value pair in JavaScript, however, it may not be the best for your needs if you need to update many keys in an object.

Method 2: Update Keys With for… in Loop

Taking the past method one step forward, we can iterate through an object in JavaScript with the for…in loop.

Below we will show the exact same solution as the one above but with the key updating happening within the loop:

const obj1 = { key1: "value1", key2: "value2", key3: "value3" };

for (const key in obj1) {
  if(key === "key1")
    obj1[key] = "updated value1";
}

console.log(obj1);

result:

[Running] node "g:\article\tempCodeRunnerFile.js"
{ key1: 'updated value1', key2: 'value2', key3: 'value3' }
 
[Done] exited with code=0 in 0.322 seconds

Although this method works as intended, there is a more… JavaScript-y way of doing things. A forEach iterator!

Method 3: Update Keys With Object.keys() and forEach()

Another popular and widely used method to update object key values is to invoke the object.keys() function to fetch all the keys in the object and then use a forEach method to iterate over the existing keys one by one, you can define the changes/updated values for each key in the object which will be changed during the iteration.

Let’s see an example of how this will actually work.

 const obj1 = {
   key1: "value1",
   key2: "value2",
   key3: "value3"
 }; // This is the starting key-value object
 
 
let keys = Object.keys(obj1); // We can also call the object.keys() method in another object variable to view the 'before' object.
console.log(keys)
 
// This will simply iterate over each key and whatever condition we have issued to the if clause will be implemented in the key object
keys.forEach(key => {
  if (key == "key3") {
    obj1[key] = "updated value3";
  }
});
 
console.log(obj1) // Prints the new key-object.

Result:

[Running] node "g:\article\tempCodeRunnerFile.js"
[ 'key1', 'key2', 'key3' ]
{ key1: 'value1', key2: 'value2', key3: 'updated value3' }
 
[Done] exited with code=0 in 0.124 seconds

Method 4: Update Keys With Object.keys() And reduce() Function

Our final way to update keys in JavaScript is to invoke the object.keys() method and pair it with the reduce() function. A built-in JavaScript feature.

The reduce() method will simply return the accumulator’s last value or which is ‘accumulated’ and the rest of the keys will be reduced to a single value.

This method is unique to the previous methods because it is immutable and creates a new object.

Let’s take a look at an example.

const obj1 = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}; //A simple key-value object by the name of 'obj1'

let keys = Object.keys(obj1);
     
let obj2 = keys.reduce((accumulator, key) => {
  return { 
    ...accumulator, 
    [key]: '' 
  };
}, {}); // A new key-value object 'obj2' with the reduce function activated, the values will be reduced to a single value and return the last value in the accumulator
     
console.log(obj2);
console.log(obj1);

Result:

[Running] node "g:\article\tempCodeRunnerFile.js"
{ key1: '', key2: '', key3: '' }
{ key1: 'value1', key2: 'value2', key3: 'value3' }
 
[Done] exited with code=0 in 0.116 seconds

This method does not write over the existing value but rather returns an entirely new key-value object for each updated value in the accumulator.

As you can see this method is a bit more complicated, but it allows you to easily copy keys into a new object, or create an operation without losing your original object.

If you want more information on the reduce() functions, check out this article.

Summary

Overall, there are four popular ways to update keys in JavaScript. You can update keys individually, loop through your keys with a for…in loop, traverse the key with a forEach() iterator, or reduce() the object to copy the keys into a new object.

These options are great ways to update keys in JavaScript because they are very common and people looking at your code will understand what you’re trying to do quickly and easily.

Hopefully, now you understand how to properly update keys in JavaScript, and as always, happy coding!

Looking for ways to level up your javascript skills? Check out these courses.

Grant Darling

Grant is a full-stack / frontend software developer passionate about writing & coding. He has many years experience working in the tech industry both as a freelancer and as an employee.

The Code Bytes is all about providing people with honest information about programming. To learn more about Grant, read his about page!

If you’re interested in freelance coding / writing services or want to partner with The Code Bytes, you can get in touch with me here!