To change a value of an object in an array in JavaScript, you can use any of the following methods –
- Use the Array.findIndex() Method.
- Change a Value using Array.map() Method.
- Use the Array.reduce() Method.
- Use the Array.forEach() Method.
Let’s discuss each of these methods in detail below.
How To Change A Value Of An Object In An Array In JavaScript
In JavaScript, arrays are versatile data structures used to store multiple values in a single variable. Often, you may find yourself needing to change a specific value within an object contained in an array.
Fortunately, JavaScript provides various methods that empower you to modify object values effortlessly. In this post, we will explore four commonly used methods: Array.findIndex(), Array.map(), Array.reduce(), and Array.forEach(). These methods offer distinct approaches to locating and updating values within objects, giving you flexibility in handling arrays of objects in JavaScript.
Let’s delve into each method and understand how to use them effectively.
Use The Array.findIndex() Method
This is the most recommended method to change a value of an object in an array. It helps you find the index of the target object and then you can use that index to update it.
Here’s an example –
var arr =
[{ name: "John", age: 25, status: "Single" },
{ name: "Jane", age: 26, status: "Married" }];
var index = arr.findIndex(obj => obj.name === "John");
if(index!=-1) {
arr[index].name = "Bob";
}
console.log(arr);
Output
[{
age: 25,
name: “Bob”,
status: “Single”
}, {
age: 26,
name: “Jane”,
status: “Married”
}]
The provided code demonstrates how to change the value of an object within an array using the Array.findIndex()
method in JavaScript. Let’s break it down step by step:
- First, an array called
arr
is declared and initialized with two objects. - The
Array.findIndex()
method is then used to find the index of the object in thearr
array whosename
property is equal to “John”: - The
findIndex()
method takes a callback function as an argument, which is executed for each element in the array. In this case, the arrow functionobj => obj.name === "John"
is used to check if thename
property of each object matches the string “John”. If a match is found, the index of that object is returned. Otherwise,-1
is returned. - The code then checks if the
index
is not equal to-1
, indicating that a match for “John” was found in the array. - If a match is found, the value of the
name
property within that object is updated to “Bob” usingarr[index].name = "Bob"
. - Finally, the modified
arr
array is logged to the console.
Change a Value Using Array.map() Method
If you want to update all values of an object in an array, or even create a new one based on some conditions, you can use the map() method.
Here’s an example –
var arr =
[{ name: "John", age: 25, status: "Single" },
{ name: "Jane", age: 26, status: "Married" }];
var updatedArray = arr.map(obj => {
if(obj.name == "John") {
return {...obj, name:"Bob"};
}
return obj;
});
console.log(updatedArray);
Output
[{
age: 25,
name: “Bob”,
status: “Single”
}, {
age: 26,
name: “Jane”,
status: “Married”
}]
The provided code demonstrates how to change the value of an object within an array using the Array.map()
method in JavaScript. Let’s break it down step by step:
- An array called
arr
is declared and initialized with two objects. - The
Array.map()
method is then used to create a new array calledupdatedArray
by iterating over each object in thearr
array. - The
map()
method creates a new array by executing a callback function on each element of the original array. In this case, the arrow functionobj => {...}
is used as the callback function. It checks if thename
property of each object is equal to “John”. - If a match is found (i.e.,
obj.name === "John"
), the object is copied using the spread syntax ({...obj}
), and thename
property within the copied object is updated to “Bob” (name: "Bob"
). This ensures that the original array (arr
) remains unaffected. - If no match is found, the original object is returned unchanged (
return obj;
). - The resulting modified array is assigned to the
updatedArray
variable. - Finally, the
updatedArray
is logged to the console. - The output will show the modified array, where the object with the
name
property equal to “John” has itsname
value changed to “Bob”.
Use the Array.reduce() Method
If you want to update or change a value of an object in an array based on some conditions, then you can use the reduce() method.
Here’s an example –
var arr =
[{ name: "John", age: 25, status: "Single" },
{ name: "Jane", age: 26, status: "Married" }];
var updatedArray = arr.reduce((accumulator, currentValue) => {
if(currentValue.name == "John") {
return accumulator.concat({...currentValue, name:"Bob"});
} else {
return accumulator.concat(currentValue);
}
}, []);
console.log(updatedArray);
Output
[{
age: 25,
name: “Bob”,
status: “Single”
}, {
age: 26,
name: “Jane”,
status: “Married”
}]
The provided code demonstrates how to change the value of an object within an array using the Array.reduce()
method in JavaScript. Let’s break it down step by step:
- An array called
arr
is declared and initialized with two objects. - The
Array.reduce()
method is used to create a new array calledupdatedArray
by iterating over each object in thearr
array. - The
reduce()
method accumulates a value by iterating over each element of the array. In this case, the accumulator starts as an empty array ([]
), and the callback function(accumulator, currentValue) => {...}
is used. - Within the callback function, it checks if the
name
property of thecurrentValue
object is equal to “John”. - If a match is found (
currentValue.name === "John"
), a new object is created using the spread syntax ({ ...currentValue }
), and thename
property within the copied object is updated to “Bob” (name: "Bob"
). - The updated object is then appended to the
accumulator
array using theconcat()
method (accumulator.concat({...currentValue, name: "Bob"})
). - If no match is found, the
currentValue
object is directly appended to theaccumulator
array (accumulator.concat(currentValue)
). - The modified array is continuously built by returning the updated
accumulator
array in each iteration of thereduce()
method. - Finally, the resulting
updatedArray
is logged to the console. - The output will show the modified array, where the object with the
name
property equal to “John” has itsname
value changed to “Bob”.
Use The Array.forEach() Method
If you want to update or change all values of an object in an array, then you can use the forEach() method.
Here’s an example –
var arr =
[{ name: "John", age: 25, status: "Single" },
{ name: "Jane", age: 26, status: "Married" }];
arr.forEach(obj => {
if(obj.name == "John") {
obj.name = "Bob";
}
});
console.log(arr);
Output
[{
age: 25,
name: “Bob”,
status: “Single”
}, {
age: 26,
name: “Jane”,
status: “Married”
}]
The provided code demonstrates how to change the value of an object within an array using the Array.forEach()
method in JavaScript. Let’s break it down step by step:
- An array called
arr
is declared and initialized with two objects. - The
Array.forEach()
method is used to iterate over each object in thearr
array. - The
forEach()
method allows you to execute a callback function for each element in the array. In this case, the arrow functionobj => {...}
is used as the callback function. - Within the callback function, it checks if the
name
property of each object is equal to “John”. - If a match is found (
obj.name === "John"
), the value of thename
property within that object is directly updated to “Bob” (obj.name = "Bob"
). This modifies the originalarr
array. - The
forEach()
method continues to iterate over the remaining objects in the array, applying the necessary updates. - Finally, the modified
arr
array is logged to the console. - The output will show the modified array, where the object with the
name
property equal to “John” has itsname
value changed to “Bob”.
Change A Value Of An Object In An Array In JavaScript
Understanding how to change values within objects in JavaScript arrays is essential for efficient data manipulation. By leveraging methods like Array.findIndex(), Array.map(), Array.reduce(), and Array.forEach(), you can locate specific objects and modify their values with ease.
Depending on your use case and requirements, you can choose the method that best suits your needs. Experiment with these methods, and you’ll gain the ability to manipulate object values within arrays effectively, expanding your JavaScript programming toolkit.
I hope this article was helpful. If you have any questions or comments, please feel free to post them below. Thanks for reading! 🙂