简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM