Add new property an object in an array javascript
A simple one!
In JavaScript, you can add a new property to an object in an array using the following methods:
Method 1: Using the push()
method
const arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
arr.push({ id: 3, name: 'Bob' });
console.log(arr); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }]
The push()
method adds a new element to the end of the array.
Method 2: Using the concat()
method
const arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
const newArr = arr.concat([{ id: 3, name: 'Bob' }]);
console.log(newArr); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }]
The concat()
method returns a new array with the original array and the new element.
Method 3: Using the spread operator
(ES6+)
const arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
const newArr = [...arr, { id: 3, name: 'Bob' }];
console.log(newArr); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' }]
The spread operator (...
) is used to spread the elements of the original array into a new array, and then the new element is added to the end.
All of these methods will add a new property to the object in the array. If you want to add a new property to an existing object in the array, you can use the find()
method to locate the object and then add the new property:
const arr = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }];
const obj = arr.find(obj => obj.id === 2);
obj.newProperty = 'Hello';
console.log(arr); // Output: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane', newProperty: 'Hello' }]