How to modify an array value of a JSON object in JavaScript?


Modifying an array is just like modifying an object when that array is inside the object. The normal general principles will apply here.

Example

In the following example, Initially in the 'companies' array, the first element is 'Tesla'. But after modifying the first element is changed to 'SolarCity' and the result is displayed in the output.

Live Demo

<html>
<body>
<script>
   var res1 = "";
   var res2 = "";
   var obj = {
      "name":"Elon musk",
      "age":48,
      "companies": [
         "Tesla", "Spacex", "Neuralink"
      ]
   }
   for (var i in obj.companies) {
      res1 += obj.companies[i] + "</br>"
   }
   document.write("Before change: " +" "+res1);
   obj.companies[0] = "SolarCity";
   for (var i in obj.companies) {
      res2 += obj.companies[i] + "</br>"
   }
   document.write("After change:" +" "+res2);
</script>
</body>
</html>

Output

Before change: Tesla
Spacex
Neuralink
After change: SolarCity
Spacex
Neuralink
raja
Published on 15-Jul-2019 18:40:28
Advertisements