Search code examples
javascriptjqueryjsonobject

how to remove json object key and value.?


I have a json object as shown below. where i want to delete the "otherIndustry" entry and its value by using below code which doesn't worked.

var updatedjsonobj = delete myjsonobj['otherIndustry'];

How to remove Json object specific key and its value. Below is my example json object where i want to remove "otherIndustry" key and its value.

var myjsonobj =  {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "[email protected]",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
    };
delete myjsonobj ['otherIndustry'];
console.log(myjsonobj);

where the log still prints the same object without removing 'otherIndustry' entry from the object.


Solution

  • delete operator is used to remove an object property.

    delete operator does not returns the new object, only returns a boolean: true or false.

    In the other hand, after interpreter executes var updatedjsonobj = delete myjsonobj['otherIndustry']; , updatedjsonobj variable will store a boolean value.

    How to remove Json object specific key and its value ?

    You just need to know the property name in order to delete it from the object's properties.

    delete myjsonobj['otherIndustry'];
    

    let myjsonobj = {
      "employeeid": "160915848",
      "firstName": "tet",
      "lastName": "test",
      "email": "[email protected]",
      "country": "Brasil",
      "currentIndustry": "aaaaaaaaaaaaa",
      "otherIndustry": "aaaaaaaaaaaaa",
      "currentOrganization": "test",
      "salary": "1234567"
    }
    delete myjsonobj['otherIndustry'];
    console.log(myjsonobj);

    If you want to remove a key when you know the value you can use Object.keys function which returns an array of a given object's own enumerable properties.

    let value="test";
    let myjsonobj = {
          "employeeid": "160915848",
          "firstName": "tet",
          "lastName": "test",
          "email": "[email protected]",
          "country": "Brasil",
          "currentIndustry": "aaaaaaaaaaaaa",
          "otherIndustry": "aaaaaaaaaaaaa",
          "currentOrganization": "test",
          "salary": "1234567"
    }
    Object.keys(myjsonobj).forEach(function(key){
      if (myjsonobj[key] === value) {
        delete myjsonobj[key];
      }
    });
    console.log(myjsonobj);