Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JSON | modify an array value of a JSON object

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The arrays in JSON (JavaScript Object Notation) are similar to arrays in Javascript. Arrays in JSON can have values of the following types:

The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modified. It can be simply done by modifying the value present at a given index. 

Example: Modifying the value present at an index in the array 

Javascript




<p id="GFG">
</p>
 
<script>
    var myObj, i, x = "";
    myObj = {
         
        // stored the values
        "words":[ "I", "am", "Good" ]
    };
     
    // modifying the value present at index 2
    myObj.words[2] = "bad";
     
    for (i in myObj.words) {
     
        // Displaying the modified content
        x += myObj.words[i] + "<br>";
    }
     
    document.getElementById("GFG").innerHTML = x;  
</script>

Output :

I
am
bad

Note: If the value is modified at an index that is out of the array size, then the new modification will not replace anything in the original information but rather will be an add-on. 

Example: Modifying the value of the index which is out of the array size. 

Javascript




<p id="GFG"></p>
 
<script>
    var myObj, i, x = "";
    myObj = {
         
        // stored values
        "words":[ "I", "am", "Good" ]
    };
     
    // trying to change a value at
    // an index out of array size
    myObj.words[3] = "bad";
     
    for (i in myObj.words) {
     
        // display the modification
        x += myObj.words[i] + "<br>";
    }
     
    document.getElementById("GFG").innerHTML = x;
</script>

Output :

I
am
Good
bad

My Personal Notes arrow_drop_up
Last Updated : 21 Dec, 2022
Like Article
Save Article
Similar Reads