How to change value of object which is inside an array using JavaScript or jQuery?

In this tutorial, we'll see how can we change the value of the object present in the array using JavaScript?
Submitted by Pratishtha Saxena, on July 22, 2022

There are some different ways in which we can change the value of array objects.

  • Using name property of an object
  • Using spread operator

Let's discuss each one of them individually.

1) Change value of object which is inside an array using name Property of Object

The name property of an object in JavaScript allows us to access the name of the respective object. Hence, using this property of object we can change the value of the object.

Syntax:

myArray[objIndex].name = "Tom"
myArray[objIndex].age = 45

The name of the array has to be mention (here myArray), and the index of the object needs to be passed as its parameter (eg: 0, 1). Here, name & age are the two objects taken into consideration.

Example 1:

<script>
   const state = {
       items : [
         {id: "A", color: "Yellow"},
         {id: "B", color: "Black"},
         {id: "C", color: "Red"},
         {id: "D", color: "Green"}
       ]}
   
       // using name property of object
       const items = state.items;
       items[1].color = "Orange";
       console.log(items);
</script>

Output:

Example 1: Change value of object

2) Change value of object which is inside an array using spread Operator

The spread operator is a simple and easy technique to immediately copy the complete array/object to a new array/object created. It is represented by three dots, i.e., ""

Syntax:

const newArray= [...ArrayOne, ...ArrayTwo];

Using this way, we can combine two arrays into a new one as shown. Therefore, using the spread operator, we will first copy the array into a new one and simultaneously replace or change the value of the object by specifying the respective object name.

Example 2:

<script>
   const state = {
       items : [
         {id: "A", color: "Yellow"},
         {id: "B", color: "Black"},
         {id: "C", color: "Red"},
         {id: "D", color: "Green"}
       ]}
   
       // using spread operator
   
       const items2 = [...state.items];
       items2[0] = {...items2[0], color: 'Violet'};
       console.log(items2);
</script>

Output:

Example 2: Change value of object





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.