How to Update Object Key Values Using Javascript?
In JavaScript, you can update object key values by accessing the object using the key and then assigning a new value to it. Here’s an example:
let person = {
name: "John",
age: 30,
city: "New York"
};
person.age = 31;
person.city = "Los Angeles";
console.log(person); // Output: { name: "John", age: 31, city: "Los Angeles" }
In this example, the person
object has three key-value pairs: name
, age
, and city
. To update the value of the age
and city
keys, we simply access the object using dot notation and assign new values to them.
Alternatively, you can also update object key values using bracket notation. Here’s an example:
let person = {
name: "John",
age: 30,
city: "New York"
};
person["age"] = 31;
person["city"] = "Los Angeles";
console.log(person); // Output: { name: "John", age: 31, city: "Los Angeles" }
In this example, we use bracket notation to access the age
and city
keys and assign new values to them.