skip to Main Content

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


  1. 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:

    data1 = data1?.map((type) => {
      const addressToUpdate = data2.unmapped.find((item) => item.id === type.id);
      if (addressToUpdate) {
        type.Details.address = addressToUpdate.address;
      }
      return type;
    });
    
    Login or Signup to reply.
  2. Firstly, your code uses map which returns a new array itself.

    Now to solve your problem, you can just do this:

    const tempData = data1;
    data1 = {
     ...tempData,
     submitted: [
      {
        ...(tempData.submitted[0]),
        Details: {
         ...(tempData.submitted[0].Details)
         address: data2.unmapped[0].address
        }
      }
     ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search