js add obj prop dynamically
How to dynamically add properties to JavaScript objects
As a web developer, I often come across situations where I need to dynamically add properties to JavaScript objects. This can be easily achieved using JavaScript.
Method 1: Using dot notation
let person = {
name: 'John',
age: 30
};
person.gender = 'Male';
console.log(person); // { name: 'John', age: 30, gender: 'Male' }
In the above code snippet, we are adding a new property 'gender' to the person object using dot notation.
Method 2: Using square bracket notation
let person = {
name: 'John',
age: 30
};
person['gender'] = 'Male';
console.log(person); // { name: 'John', age: 30, gender: 'Male' }
In the above code snippet, we are adding a new property 'gender' to the person object using square bracket notation.
Method 3: Using Object.assign()
let person = {
name: 'John',
age: 30
};
let newProperty = { gender: 'Male' };
let updatedPerson = Object.assign(person, newProperty);
console.log(updatedPerson); // { name: 'John', age: 30, gender: 'Male' }
In the above code snippet, we are adding a new property 'gender' to the person object using Object.assign() method.
Method 4: Using spread operator
let person = {
name: 'John',
age: 30
};
let updatedPerson = {...person, gender: 'Male'};
console.log(updatedPerson); // { name: 'John', age: 30, gender: 'Male' }
In the above code snippet, we are adding a new property 'gender' to the person object using spread operator.
These are the four methods to dynamically add properties to JavaScript objects. Depending on the situation, we can choose the appropriate method to achieve the desired result.