Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on.
JSON arrays are written inside square brackets.
Just like in JavaScript, an array can contain objects:
Example(1)
Create JSON array Values
myObj = { "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] };
Modify Array Values
Use the index number to modify an array:
var myObj, i, x = ""; myObj = { "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] }; myObj.cars[1] = "Mercedes";
Complete Code For Modifying JSON Array Elements Using JavaScript.
<!DOCTYPE html> <html> <head> <title>How To Modify JSON Array Elements Using JavaScript</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> </head> <body> <div class="container"> <br> <div class="text-center"> <h1 id="color" style="color: tomato">How To Modify JSON Array Elements Using JavaScript</h1> </div> <br> <div class="well"> <h2 id="demo1"></h2> </div> <script> var myObj, i, x = ""; myObj = { "name":"John", "age":30, "cars":[ "Ford", "BMW", "Fiat" ] }; myObj.cars[1] = "Mercedes"; for (i in myObj.cars) { x += myObj.cars[i] + "<br>"; } document.getElementById("demo1").innerHTML = x; </script> </div> </body> </html>