How to usethe for-of loop in Javascript
Using a for loop to traverse an array of objects, finding and modifying the property of a specific object as per a condition.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, we will try to use the same array of objects which we have created previously, and then we will use the for-of loop in order to update the existing object’s property’s value.
let employees_data = [
{
employee_id: 1,
employee_name: "Aman",
},
{
employee_id: 2,
employee_name: "Bhargava",
},
{
employee_id: 3,
employee_name: "Chaitanya",
},
];
for (let object of employees_data) {
if (object.employee_id === 2) {
object.employee_name = "Anthony";
}
}
console.log("Updated Data: ");
console.log(employees_data);
Output
Updated Data: [ { employee_id: 1, employee_name: 'Aman' }, { employee_id: 2, employee_name: 'Anthony' }, { employee_id: 3, employee_name: 'Chaitanya' } ]
How to modify an object’s property in an array of objects in JavaScript ?
Modifying an object’s property in an array of objects in JavaScript involves accessing the specific object within the array and updating its property. In this article we are going to see how to modify an object’s property in an array of objects in JavaScript
Below are the approaches to modify an object’s property in an array of objects in JavaScript:
Table of Content
- Approach 1: Using the Array.map() method
- Approach 2: Using the for-of loop
- Approach 3: Using Array.map() with spread operator
- Approach 4: Using forEach() method
- Approach 5: Using the find() method and destructuring
- Approach 6: Using Array.reduce() Method
- Approach 7: Using Array.filter() and Array.concat() Methods