How To Update An Object’s Property In Array Of Objects In JavaScript

When working with arrays in JavaScript, we often need to update an object’s property in an array of objects. This article will guide you in two ways: using the Array.map() method and using the forEach loop

Update An Object’s Property In Array Of Objects In JavaScript

Using the Array.map() method

The Array.map() method in JavaScript is a method that allows us to create a new array from an existing array by calling a function on each element in the parent array after iterating through the array.

To update an object’s property in an array of objects in JavaScript, we utilize the Array.map() method to iterate through the elements of the array. This step is used to find the object that needs to be updated. After we have found the object we are looking for, we use the JavaScript spread operator(…) to update that object. The spread operator(…) is intended to preserve the elements of the array and only return and update the object’s property value that needs to be updated.

For example:

const car = [
	{ id: 1, name: "Toyota" },
	{ id: 2, name: "BMW" },
	{ id: 3, name: "Lexus" },
	{ id: 4, name: "Ford" },
];

let newCar = car.map((element) => {
	// Set conditions to search for objects
	if (element.id === 1) {
		// Update the object's property value
		return { ...element, name: "Mercedes" };
	}

	return element;
});

console.log("After update:");
console.log(newCar);

Output:

After update:
{id: 1, name: 'Mercedes'}
{id: 2, name: 'BMW'}
{id: 3, name: 'Lexus'}
{id: 4, name: 'Ford'}

The name of the object with id=1 has been updated to “Mercedes” while the other objects are preserved.

Using the forEach loop

Another way to update an object’s property in an array of objects in JavaScript is to use a forEach loop. With this approach, we use a forEach loop to iterate over each object in the array. When the object is found, we will proceed to update the object’s property value.

For example:

const car = [
	{ id: 1, name: "Toyota" },
	{ id: 2, name: "BMW" },
	{ id: 3, name: "Lexus" },
	{ id: 4, name: "Ford" },
];

car.forEach(function (car) {
	// Set conditions to search for objects
	if (car.id === 1) {
		// Update the object's property value
		car.name = "Mercedes";
	}
});

console.log("After update:");
console.log(car);

Output:

After update:
{id: 1, name: 'Mercedes'}
{id: 2, name: 'BMW'}
{id: 3, name: 'Lexus'}
{id: 4, name: 'Ford'}

Besides using forEach, we can also update an object’s property in an array of objects through another loop, like for loop, with the same approach as the forEach loop.

Summary

Through this article, you have learned how to update an object’s property in an array of objects in JavaScript in two ways. Both methods are common and accessible, so you can easily use them in your project. I hope your project will be successful using the two methods above.

Leave a Reply

Your email address will not be published. Required fields are marked *