0

Is there a quick and stable way to remove all a key value pair from a json Doc array. In my case i have data returned from my DB which contains more fields then i want to show to user so i want to query my db and see what key's he is supposed to get before returning the json to client. In this sample the data has 3 keys, FirstName,LastName and dob how would i go to remove all dob Key and values from the json, also if i have to remove more then one Key Value pair does it make difference when you do it ?

{
"result":[
   {
       "FirstName": "Test1",
       "LastName":  "User",
       "dob":  "01/01/2011"
   },
   {
       "FirstName": "user",
       "LastName":  "user",
       "dob":  "01/01/2017"
   },
   {
       "FirstName": "Ropbert",
       "LastName":  "Jones",
       "dob":  "01/01/2001"
   },
   {
       "FirstName": "hitesh",
       "LastName":  "prajapti",
       "dob":  "01/01/2010"
   }

] }

MisterniceGuy
  • 1,646
  • 2
  • 18
  • 41
  • Possible duplicate of [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – Bryan Euton Aug 11 '18 at 01:16

1 Answers1

1

You can use the delete operator on the obj while looping through your data.

let data = {
  "result": [{
      "FirstName": "Test1",
      "LastName": "User",
      "dob": "01/01/2011"
    },
    {
      "FirstName": "user",
      "LastName": "user",
      "dob": "01/01/2017"
    },
    {
      "FirstName": "Ropbert",
      "LastName": "Jones",
      "dob": "01/01/2001"
    },
    {
      "FirstName": "hitesh",
      "LastName": "prajapti",
      "dob": "01/01/2010"
    }
  ]
}

// @param keys: an array of keys to remove
function removeKeyValue(obj, keys) {
  obj.forEach(currObj => {
    keys.forEach(key => {
      delete currObj[key];
    });
  });
}

removeKeyValue(data.result, ["dob", "LastName"]);
console.log(data.result);
Andrew Lohr
  • 5,380
  • 1
  • 26
  • 38