Search code examples
reactjstypescriptreact-typescript

How to modify complex JSON data


I have below JSON data & I need to modify the values or remove some properties.

 {
"actions": {
"canUpdateAbc": true,
"canUpdateXyz": true  
},
"criteria": [
{
  "criteriaType": {
    "code": "CCode",
    "value": "C Code"
  },
  "processType": {
    "code": "PType",
    "value": "C"
  },
  "values": [
    "123456"
  ]
},
{
  "criteriaType": {
    "code": "ACode",
    "value": "A Code"
  },
  "processType": {
    "code": "PType",
    "value": "R"
  },
  "values": [
    "567890"
  ]
}
],
"outcome": {
"code": "create",
"value": "Always create"
},
"unlessCriteria": []
}

& I need to modify processType. i.e processType = undefined or need to remove the property.

Output should be

{
"actions": {
"canUpdateAbc": true,
"canUpdateXyz": true  
},
 "criteria": [
 {
  "criteriaType": {
    "code": "CCode",
    "value": "C Code"
  },      
  "values": [
    "123456"
  ]
},
{
  "criteriaType": {
    "code": "ACode",
    "value": "A Code"
  },     
  "values": [
    "567890"
  ]
}
],
"outcome": {
"code": "create",
"value": "Always create"
},
"unlessCriteria": []
}

I have tried like this..

 const rules = rule.criteria?.map((m) => {
    m.processType = undefined;
    return m;
   });

& Its not working. I get only criteria, not entire JSON data.

How to achieve in Typescript?


Solution

  • Use the spread operator ... to spread the original object. This should work:

    const rules = {
      ...rule,
      criteria: rule.criteria?.map((m) => {
        m.processType = undefined;
        return m;
      }),
    };
    

    You can consider delete m.processType instead of setting it to undefined, if you prefer.

    Alternatively, you can use this if you don't mind mutating the original object:

    rule.criteria?.forEach((m) => {
        delete m.processType;
    })