How to Remove a Property from an Object in JavaScript

JSON alias 'JavaScript Object Notation' is the string representation of JavaScript Object and is a popular data-exchange format among web-services. Manipulating those data received from various source is an essential skill required for every developer. With that in mind we have published several json tutorials in the past which discusses about working with json data. And today in this tutorial, we'll see how to remove a property from an object in javascript.

how to remove a property from an object in javascript

Removing a Property from JavaScript Object

Let's say we have a Java Script Object that contains three properties (details) of an employee namely 'name', 'gender' & 'position'.

{"name": "Garrett Winters","gender": "Male","position": "Javascript Developer"}

Now we want to remove one of the properties from the above object and to do this, we have to use java script's delete method. Here's the code snippet for removing the 'gender' property.

<script type="text/javascript">
    var obj = {"name": "Garrett Winters","gender": "Male","position": "Javascript Developer"};

    delete obj.gender;
    console.log(JSON.stringify(obj));
</script>

// produces output

// {"name":"Garrett Winters","position":"Javascript Developer"}

delete obj.gender statement will remove the property 'gender' from the object 'obj'. Alternatively using delete obj['gender'] will also produce the same result.

JSON.stringify will convert the javascript object to string format.

Removing a Property from Array of Objects

The above method works well for a single object, but that would not be the case always. What if you want to remove a particular property from an array of objects like this?

[{"name":"Garrett Winters","gender":"Male","position":"Javascript Developer"},{"name":"Colleen Hurst","gender":"Female","position":"System Architect"},{"name":"Michael Frost","gender":"Male","position":"Marketing Designer"}]

In this case, you should tweak the previous code a little bit to loop through the array and delete the properties one by one. Here's the script for doing it.

<script type="text/javascript">
    var obj = [{"name": "Garrett Winters", "gender": "Male", "position": "Javascript Developer"}, {"name": "Colleen Hurst", "gender": "Female",  "position": "System Architect"}, {"name": "Michael Frost", "gender": "Male", "position": "Marketing Designer"}];

    for (var i = 0; i < obj.length; i++) {
        delete obj[i].gender;
    }
    console.log(JSON.stringify(obj));
</script>

// produces output

// [{"name":"Garrett Winters","position":"Javascript Developer"},{"name":"Colleen Hurst","position":"System Architect"},{"name":"Michael Frost","position":"Marketing Designer"}]
Read Also:

That was all about removing the property from javascript object. You can easily remove properties from complex & nested java script objects similarly with this method.

No comments:

Post a Comment