I have below JSON data called data1.
{
"submitted": [
{
"id": "123",
"status": {
"code": "unmapped",
"value": "Unmapped"
},
"Type": {
"code": "I",
"value": "Institutional"
},
"Responsibility": {
"code": "P",
"value": "Primary"
},
"Details": {
"payerId": "456",
"name": "Bla Bla",
"enabled": false,
"address": {}
}
}
],
"XyzDetails": {
"id": "1",
"name": "bla",
"Level": {
"code": "S",
"value": "Secondary"
}
}
}
And another JSON data called data2
{
"unmapped": [
{
"id": "123",
"address": {
"addressLine1": "P.O. BOX 981106",
"city": "EL PASO",
"state": "TX",
"zip": "79998"
}
}
]
}
I need to update the address of first JSON data1 with JSON data2.
I have written below code and it takes address as Array of object instead of just JSON object.
data1 = data1?.map((type) => {
type.Details.address = data2.unmapped
?.filter((item) => item.id === type.id)
.map((item) => item.address);
return type;
});
I am getting below result.
"address": [
{
"addressLine1": "P.O. BOX 981106",
"city": "EL PASO",
"state": "TX",
"zip": "79998"
}
]
Instead of
"address":{
"addressLine1": "P.O. BOX 981106",
"city": "EL PASO",
"state": "TX",
"zip": "79998"
}
What is the wrong in my code? how to achieve this?
2
Answers
To update the address of data1 with the address from data2, you can directly assign the address object instead of using the map function. Also, since there is only one address object that needs to be assigned, you can use the find function instead of filter. Here’s the updated code:
Firstly, your code uses map which returns a new array itself.
Now to solve your problem, you can just do this: