Table of Contents
In this article, we will see different methods to update key with new value in JavaScript. If you have been working with Javascript then there might be a chance that you come across this use case or a closely related error: Object has no method push. Javascript treats the variables within an object as keys. Many times, it might so happen you need to dynamically update the values of an object in Javascript. After all, Javascript is all about flexibility. During that time, developers can either push or add more keys into an object at run time using methods explained in below section.
How to Update Key with new value in JavaScript [3 Methods]
Also Read: Solved "objects are not valid as a react child" error in React JS
Unlike strongly typed languages such as Java, or C#, Javascript is loosely typed. While this nature of Javascript is loved by many developers, it also leads to runtime errors when manipulating the data. Below we will see how this error use case can be handled without crashing the code.
Using jQuery
The jQuery is an extremely popular Javascript library to manipulate JS and DOM. Using jQuery, we can modify the keys like below shown example:-
function usingJquery() { // Initialize a new object let jsObj = { id: 1, age: 23, title: "some title" }; // Use the jQuery selector to iterate over the object $.each(jsObj, function(index) { // If the index is title, update the value if (index == "title") jsObj[index] = "New modification" }); // Print the new value console.log(jsObj) }
Make sure to add the jQuery resources to your application to make the above code work. JQuery is available for all major Javascript package managers including npm. The CDN link is also available on their website to download.
Introducing a new key in Object
We begin our journey by adding a new key in the Javascript object. The below code simply adds a new key to the object.
// Add a new key to this object function addAnotherKey() { let jsObj = { id: 1, age: 23, title: "some title" }; // Add a new key jsObj.newKey = "some new key"; // Add a new key with Array jsObj.newArray = ["1", "2", "3"]; }
Using Object.keys
Now suppose we had to update the value of the key dynamically, we could iterate using Object.keys method.
// Use Object Keys function updateUsingObjectKeys() { // A sample JS object let jsObj = { id: 1, age: 23, title: "some title" }; // Fetch all the keys(variables) from the object let keys = Object.keys(jsObj); console.log(keys) // [id, age, title] // Iterate over each key keys.forEach(element => { // If the element is title update its value if (element == "title") { jsObj[element] = "A new title"; } }); console.log(jsObj) // [title: "A new title"] }
Using forEach and map
The forEach and map functions in Javascript allow iteration over a collection of variables/objects. With each iteration, we can get an object from the collection and hence can manipulate the values. If our array consists of complex objects, we can also iterate over the keys in the object to update the values.
// Use the map function to modify arrays function usingMapFunction() { // Initialize the array let myArray = ["one", "two", "three", "four", "five"]; // Iterate over the collection of objects // The final array returned is the updated array myArray = myArray.map(element => { if (element == "three") element = "three modified" return element; }); // Print out the array console.log(myArray) // A more complex example let myJsonArray = [ { id: 1, name: "some name1", age: 21}, { id: 2, name: "some name2", age: 22} ] // Iterate over the whole array getting one object at a time myJsonArray = myJsonArray.map( obj => { // Get the keys of the object Object.keys(obj).forEach(key => { // If the key is id and the value of the key is 1 if (key == "id" && obj[key] == 1) obj["name"] = "Name modified" // Make an update for checking purposes }); // Return is needed so that new array could be prepared return obj; }); // Printing out the final array console.log(myJsonArray) }
Conclusion
Any production-grade application should not crash in any scenario. However, adding exception handles everywhere is also not the solution. A better option is always to mitigate the potential situations causing the errors, rather than catching the exceptions.
One such scenario is when the keys are either not present in the object or the object is not manipulated as per the type. In this post, we looked at some methods provided by Javascript that can effectively perform checks and manipulate the object legally without crashing the application. Notice that in each of the code samples, we use the if statement to avoid crashing the application.