Adding new member into an object
In JavaScript, you can add a new property (or member) to an object using the dot notation or the bracket notation.
Dot Notation
const person = { name: 'John', age: 30 };
person.email = '[email protected]';
console.log(person); // Output: { name: 'John', age: 30, email: '[email protected]' }
In this example, we create an object person
with two properties: name
and age
. We then add a new property email
using the dot notation.
Bracket Notation
const person = { name: 'John', age: 30 };
person['phone'] = '123-456-7890';
console.log(person); // Output: { name: 'John', age: 30, phone: '123-456-7890' }
In this example, we create an object person
with two properties: name
and age
. We then add a new property phone
using the bracket notation.
Using the Object.assign()
method
const person = { name: 'John', age: 30 };
const newProperty = { email: '[email protected]' };
Object.assign(person, newProperty);
console.log(person); // Output: { name: 'John', age: 30, email: '[email protected]' }
In this example, we create an object person
with two properties: name
and age
. We then create a new object newProperty
with a single property email
. We use the Object.assign()
method to merge the two objects, adding the new property to the original object.
Using the Spread Operator
(ES2018+)
const person = { name: 'John', age: 30 };
const newProperty = { email: '[email protected]' };
person = {...person,...newProperty };
console.log(person); // Output: { name: 'John', age: 30, email: '[email protected]' }
In this example, we create an object person
with two properties: name
and age
. We then create a new object newProperty
with a single property email
. We use the spread operator (...
) to merge the two objects, adding the new property to the original object.
Note that in all cases, the new property is added to the original object, and the object is updated in place.