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"
   }

] }

1

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, any chance to remove more then 1 KeyValue at time or would i have to loop over the loop ?
@MisterniceGuy I updated the example to take multiple keys to delete. Loop through the keys to delete for each obj.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.