I have to update a value in a JSON object based on the variable "id". So in the next JSON array when the id = "746936" the isSendstatus property of that JSON object must be set to true.
This is my input
var xyz = [
{
"referenceId": "WRK-2403472",
"taskReferenceId": "440827",
"textMessages": [
{
"id": "746935",
"isSendStatus": false,
"message": "test1"
},
{
"id": "746936",
"isSendStatus": false,
"message": "test2"
}
]
},
{
"referenceId": "WRK-2403470",
"taskReferenceId": "440828",
"textMessages": [
{
"id": "746935",
"isSendStatus": false,
"message": "test3"
}
]
}
]
And when I do a map and rebuild the JSON again with this code then it runs fine.
xyz map (item,index) -> {
(referenceId : item.referenceId) if (item.referenceId != null),
(taskReferenceId: item.taskReferenceId) if (item.taskReferenceId != null),
(textMessages: item.textMessages map {
id: $.id,
isSendStatus: if(($.id == "746936") and (item.taskReferenceId == "440827")) true else $.isSendStatus,
message: $.message
}) if (item.textMessages != null)
}
This is the right output:
[
{
"referenceId": "WRK-2403472",
"taskReferenceId": "440827",
"textMessages": [
{
"id": "746935",
"isSendStatus": false,
"message": "test1"
},
{
"id": "746936",
"isSendStatus": true,
"message": "test2"
}
]
},
{
"referenceId": "WRK-2403470",
"taskReferenceId": "440828",
"textMessages": [
{
"id": "746935",
"isSendStatus": false,
"message": "test3"
}
]
}
]
But it is a lot of code and Mulesoft also has an update operator and function, I tried a couple of things like this but none of them give the right result:
// attempt 1
xyz map ($ update {
case .textMessages["746936"].isSendStatus -> true
})
// attempt 2
xyz map(item,index) -> (item update ["textMessages"] with (if ($.id == "746936")
{
id: $.id,
isSendStatus: true,
message: $.message
}
else
$
)
)
But when using the update operator or function it does not work. I think the problem is that the update function or operator has problems with arrays.
2
Answers
I would not say it is a lot of code. Using the update operator may not reduce the size of the code, but perhaps more importantly for maintenance you could make changes that will communicate better the intention of the code.
Instead of null checks per key you can use filterObject() to remove all keys with null values.
The update operator doesn’t has an issue with arrays.
Replacing the remaining condition with the update operator may be considered a question of style but it allows you to map only the fields that need to change.
To test I added an item with null values.
Example input:
Output:
You can also use the
update function
as opposed to theupdate operator
. I find it cleaner with used with Arrays as you do not have to usemap
function to handle updation per element. It also makes the code more readable.