Skip to content

Remove key/value pairs in JSON using javascript

I have JSON that looks like this:

{
  "primary": {
    "value": "#0093c1",
    "type": "color"
  },
  "background": {
    "value": "#f2f2f2",
    "type": "color"
  },
  "foreground": {
    "value": "#000000",
    "type": "color"
  },
  "secondary": {
    "value": "#32c100",
    "type": "color"
  },
  "alert": {
    "value": "#c10000",
    "type": "color"
  }
}

How do I first check if each has a type and if so, then remove all type key/value pairs no matter how nested they might be?

Answer

try this

Object.keys(obj).forEach((prop) => {
  delete obj[prop].type; 
 });

result

{
  "primary": {
    "value": "#0093c1"
  },
  "background": {
    "value": "#f2f2f2"
  },
  "foreground": {
    "value": "#000000"
  },
  "secondary": {
    "value": "#32c100"
  },
  "alert": {
    "value": "#c10000"
  }
}