Change A Value Of An Object In An Array In JavaScript

change a value of an object in an array in JavaScript
change value of object in array js

To change a value of an object in an array in JavaScript, you can use any of the following methods –

  1. Use the Array.findIndex() Method.
  2. Change a Value using Array.map() Method.
  3. Use the Array.reduce() Method.
  4. 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:

  1. First, an array called arr is declared and initialized with two objects.
  2. The Array.findIndex() method is then used to find the index of the object in the arr array whose name property is equal to “John”:
  3. The findIndex() method takes a callback function as an argument, which is executed for each element in the array. In this case, the arrow function obj => obj.name === "John" is used to check if the name property of each object matches the string “John”. If a match is found, the index of that object is returned. Otherwise, -1 is returned.
  4. The code then checks if the index is not equal to -1, indicating that a match for “John” was found in the array.
  5. If a match is found, the value of the name property within that object is updated to “Bob” using arr[index].name = "Bob".
  6. 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:

  1. An array called arr is declared and initialized with two objects.
  2. The Array.map() method is then used to create a new array called updatedArray by iterating over each object in the arr array.
  3. The map() method creates a new array by executing a callback function on each element of the original array. In this case, the arrow function obj => {...} is used as the callback function. It checks if the name property of each object is equal to “John”.
  4. If a match is found (i.e., obj.name === "John"), the object is copied using the spread syntax ({...obj}), and the name property within the copied object is updated to “Bob” (name: "Bob"). This ensures that the original array (arr) remains unaffected.
  5. If no match is found, the original object is returned unchanged (return obj;).
  6. The resulting modified array is assigned to the updatedArray variable.
  7. Finally, the updatedArray is logged to the console.
  8. The output will show the modified array, where the object with the name property equal to “John” has its name 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:

  1. An array called arr is declared and initialized with two objects.
  2. The Array.reduce() method is used to create a new array called updatedArray by iterating over each object in the arr array.
  3. 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.
  4. Within the callback function, it checks if the name property of the currentValue object is equal to “John”.
  5. If a match is found (currentValue.name === "John"), a new object is created using the spread syntax ({ ...currentValue }), and the name property within the copied object is updated to “Bob” (name: "Bob").
  6. The updated object is then appended to the accumulator array using the concat() method (accumulator.concat({...currentValue, name: "Bob"})).
  7. If no match is found, the currentValue object is directly appended to the accumulator array (accumulator.concat(currentValue)).
  8. The modified array is continuously built by returning the updated accumulator array in each iteration of the reduce() method.
  9. Finally, the resulting updatedArray is logged to the console.
  10. The output will show the modified array, where the object with the name property equal to “John” has its name 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:

  1. An array called arr is declared and initialized with two objects.
  2. The Array.forEach() method is used to iterate over each object in the arr array.
  3. The forEach() method allows you to execute a callback function for each element in the array. In this case, the arrow function obj => {...} is used as the callback function.
  4. Within the callback function, it checks if the name property of each object is equal to “John”.
  5. If a match is found (obj.name === "John"), the value of the name property within that object is directly updated to “Bob” (obj.name = "Bob"). This modifies the original arr array.
  6. The forEach() method continues to iterate over the remaining objects in the array, applying the necessary updates.
  7. Finally, the modified arr array is logged to the console.
  8. The output will show the modified array, where the object with the name property equal to “John” has its name 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! 🙂

Leave a Reply