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?
4
Answers
Use the spread operator
...
to spread the original object. This should work:You can consider
delete m.processType
instead of setting it toundefined
, if you prefer.Alternatively, you can use this if you don’t mind mutating the original object:
Here is an another possible solution
parse the JSON data into object => Modify
processType
property within each object incriteria
array => convert the modified object back into a JSON string.You could also do it this way:(personally, I like the above answer by twharmon)
Now if you see rules object, criteria will have your required processType. This is because "The map() method creates a new array populated with the results of calling a provided function on every element in the calling array."
I think what you need is not to reassign the
rule
value with only the criterias array inside, let’s call your json data isdata
, you should rewrite your code like belowThis code keeps all data property and reassign only criteria array with
processType
in criteria item has been reassign to undefined. Hope this help !