Adding a new value to an object
In JavaScript, you can add a new value to an object using the following methods:
- Assignment: You can assign a new value to a property that doesn't exist in the object using the dot notation or bracket notation.
Example:
const person = {};
person.name = 'John'; // adds a new property "name" with value "John"
- Bracket notation: You can use the bracket notation to add a new property to the object.
Example:
const person = {};
person['age'] = 30; // adds a new property "age" with value 30
- Object spread: You can use the object spread operator (
{... }
) to add new properties to an object.
Example:
const person = { name: 'John' };
person = {...person, age: 30 }; // adds a new property "age" with value 30
- Object.assign: You can use the
Object.assign
method to add new properties to an object.
Example:
const person = { name: 'John' };
Object.assign(person, { age: 30 }); // adds a new property "age" with value 30
- Dynamic property names: You can use a variable to create a dynamic property name and add a new value to the object.
Example:
const person = {};
const propertyName = 'age';
person[propertyName] = 30; // adds a new property "age" with value 30
Note that if the property already exists in the object, the new value will overwrite the existing value.