In this post, we are going to learn how to add multiple properties to an array of objects in JavaScript.We are going to learn with example by using different ways those are using foreach loop, for of loop, and map() function.
1. Foreach loop to Add multiple properties to an array of objects
By using Javascript for-each loop we can add single or multiple properties to an array of objects. In this javascript program, we are iterating over an array of objects and adding two properties with key and values pair Emp.Address = ‘Us’,Emp.Phone = 123456.
let Employee = [
{Empname: 'John',EmpID:1,Dep:'Admin'},
{Empname: 'jack', EmpID:2,Dep:'IT'}
]
Employee.forEach(Emp => {
Emp.Address = 'Us',
Emp.Phone = 123456;
});
console.log(Employee)
Output
[
{
Empname: 'John',
EmpID: 1,
Dep: 'Admin',
Address: 'Us',
Phone: 123456
}, {
Empname: 'jack',
EmpID: 2,
Dep: 'IT',
Address: 'Us',
Phone: 123456
}
]
2. Map() with spread operator to add multiple properties to an object array
The array.map() method is iterated over the element of the array and modifies elements of the array by applying some operation and returning the modified element as a new array. In this Javascript example, we apply a function along with a spread operator to add multiple properties to an array of objects.
let Employee = [
{Empname: 'John',EmpID:1,Dep:'Admin'},
{Empname: 'jack', EmpID:2,Dep:'IT'}
]
const updateObj = Employee.map(Emp => {
return {...Emp, Address:'Us',Phone :123456}
});
console.log(updateObj)
Output
[
{
Empname: 'John',
EmpID: 1,
Dep: 'Admin',
Address: 'Us',
Phone: 123456
},
{
Empname: 'jack',
EmpID: 2,
Dep: 'IT',
Address: 'Us',
Phone: 123456
}
]
3. For of loop to Add multiple properties to an array of object
In this JavaScript program, we have used for loop to iterate over each object in an array of objects and modified each object by adding two properties emp.Phone = 98964532,emp.address = ‘Us’ into it.Let us understand with an example.
let Employee = [
{Empname: 'John',EmpID:1,Dep:'Admin'},
{Empname: 'jack', EmpID:2,Dep:'IT'}
]
for(const emp of Employee) {
emp.Phone = 98964532,
emp.address = 'Us'
}
console.log(Employee)
Output
[
{
Empname: 'John',
EmpID: 1,
Dep: 'Admin',
Phone: 98964532,
address: 'Us'
},
{
Empname: 'jack',
EmpID: 2,
Dep: 'IT',
Phone: 98964532,
address: 'Us'
}
]
Summary
In this post, we have learned multiple ways how to add multiple properties to the array of objects in JavaScript with examples by using the foreach loop, for of loop, and map() function.