How To Delete JSON Array Elements Using JavaScript

admin_img Posted By Bajarangi soft , Posted On 08-10-2020

In Java Script we can delete json array data with index values so today we discuss how to delete array elements using java script

How To Delete JSON Array Elements Using JavaScript

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

var myObj, i, x = "";
myObj = {
    "name":"John",
    "age":30,
    "cars": ["Ford","BMW","Fiat"]
}
 

Delete Array Items

Use the delete keyword to delete items from an array:

delete myObj.cars[1];


Complete Code For Deleting JSON Array Elements Using JavaScript.

<!DOCTYPE html>
<html>
<head>
    <title>How To Delete 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 Delete 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"]
        }
        delete myObj.cars[1];

        for (i in myObj.cars) {
            x += myObj.cars[i] + "<br>";
        }
        document.getElementById("demo1").innerHTML = x;
    </script>
</div>
</body>
</html>

 

Related Post