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


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.