Update key with new value in JavaScript [SOLVED]


NodeJS

How to update key with new value in JavaScript

Data stored within any data structure need to be updated - Objects inclusive. Updating one value can be relatively easy, but if we want to update all the values of the Object, we need a more comprehensive approach to cover such. That’s what the article intends to explain.

Within objects (unless empty), we have at least one property-value pair, and to update the value of the property (also called key), we can simply use the bracket notation

let obj = {
    name: "david",
};

obj["name"] += " mouse";

console.log(obj);

Output:

{ name: 'david mouse' }

The above code adds to the string value bound to the name key. However, if we need to update all the value of the object, we need an efficient and simple algorithm. That’s where forEach and map in JavaScript come in.

 

Method-1: Use forEach to update key with new value

We have an object, and therefore, there is a means to iterate over it. We can use the iterative process obtain each key and apply the bracket notation to obtain each value and manipulate it as we please.

Let’s take a simple data that contain scores of five students stored within the scores binding and print each score using foreach loop.

let scores = {
    abel: 45.6,
    brian: 34.6,
    caroline: 39.8,
    david: 24.5
}

for (let key in scores) {
    console.log(scores[key]);
}

Output:

45.6
34.6
39.8
24.5

Say we want to add five more marks to each score because there was an error in the exam, we can update each value using the same code with just a little addition

for (let key in scores) {
    scores[key] += 5;
}

console.log(scores)

Output:

{ abel: 50.6, brian: 39.6, caroline: 44.8, david: 29.5 }

With these we have achieved the goal to update key with new value, however, we can create a more composed code for this using the Object.keys() and forEach method.

The Object.keys() returns the names of the enumerable string properties and methods of an object within an array, and the forEach() method performs a specific action which is passed as an argument to each element within the array.

console.log(Object.keys(scores));

Output:

[ 'abel', 'brian', 'caroline', 'david' ]

Similarly, forEach() in action

let arr = [1, 2, 3, 4, 5]
arr.forEach(x => {
    console.log(x);
});

Output:

1
2
3
4
5

We will use the Object.keys() method to obtain an array containing the names of the student within the scores object, and pass the array returned to the forEach method which will hold an anonymous function that will update the value with the bonus five marks.

let scores = {
    abel: 45.6,
    brian: 34.6,
    caroline: 39.8,
    david: 24.5
}

Object.keys(scores).forEach((name) => (scores[name] += 5));

console.log(scores);

Output:

{ abel: 50.6, brian: 39.6, caroline: 44.8, david: 29.5 }

And like that we can update key with new value within an object data type.

 

Method-2: Use map to update key with new value

Just as we created a composed code using the Objects.keys() method and forEach() method, we can do the same with Object.keys() and the maps() method.

The maps() method like the forEach() method is a higher-order function that works with arrays by calling a function on each element of the array and returns an array with the result.

let arr = [1, 2, 3, 4, 5]
arr.map(x => {
    console.log(x + 2);
});

Output:

3
4
5
6
7

The function that contains a console.log() statement is called on each element within the arr array.

Now, let’s apply the map() method on the Object.keys() to update the scores of the students.

let scores = {
    abel: 45.6,
    brian: 34.6,
    caroline: 39.8,
    david: 24.5
}

Object.keys(scores).map((name) => (scores[name] += 5));

console.log(scores);

Output:

{ abel: 50.6, brian: 39.6, caroline: 44.8, david: 29.5 }

 

Summary

To update key with new value especially across the entire object, the use of composable code is efficient and easier. The Object.keys(), forEach(), and map() methods help achieve the goal of updating the keys. The linkage between the methods where the results of the first method is passed to the second method is functional helped in achieving the result.

 

Further Readings

Array.prototype.forEach() - JavaScript | MDN (mozilla.org)
Object.keys() - JavaScript | MDN (mozilla.org)
Updating existing object values using best way
map function for objects (instead of arrays)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment