This is my payload, here I need to validate the status field as active or inactive in details.addressDesc
array
{
"id": "123",
"address": [
{
"type": "ABC",
"name": "name"
}
],
"details": [
{
"Firstname": "firstname1",
"lastname": "lastname1",
"addressDesc": [
{
"desc": "home",
"status": "active"
},
{
"desc": "office",
"status": "inactive"
}
]
},
{
"Firstname": "firstname2",
"lastname": "lastname2",
"addressDesc": [
{
"desc": "home",
"status": "inactive"
},
{
"desc": "office",
"status": "active"
}
]
},
{
"Firstname": "firstname3",
"lastname": "lastname3",
"addressDesc": [
{
"desc": "home",
"status": "active"
},
{
"desc": "office",
"status": "active"
}
]
}
]
}
If status is active
, corresponding names(from details)
should be clubbed with its desc(details.addressDesc)
If all the elements of status is active, then corresponding number of nameDetails should be created (here firstname3 has both the status as active)
Expected Output is as below.
{
"addressDetails": [
{
"Firstname": "firstname1",
"lastname": "lastname1",
"addressName": "home",
"status": "active"
},
{
"Firstname": "firstname2",
"lastname": "lastname2",
"addressName": "office",
"status": "active"
},
{
"Firstname": "firstname3",
"lastname": "lastname3",
"addressName": "home",
"status": "active"
},
{
"Firstname": "firstname3",
"lastname": "lastname3",
"addressName": "office",
"status": "active"
}
]
}
2
Answers
In this kind of problems it is easier to discompose it in steps. First get the array you are interested
payload.details
then the trick is for each element to map not the element but the nested oneaddressDesc
. Using different names for the mapping operations allows to use values from the parent element. Then convert map() to flatMap() as needed or use flatten().Try the below code.
Here you can iterate over the details array, then iterate over the addressDesc array for each detail, and filter based on the status being "active".