Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding new property to object of arrays

I have policyNumbers array, and I want to add it to current each policy.
Problem is that for each object it’s adding every policy number. I just need for one policy one number,
I have 3 policies and 3 policy numbers.

Each object must have only one policy number, how can I fix this?

      const travelersInfoWithPolicyNumbers = payload.travelersInfo.map((traveler) => ({
        ...traveler,
        policyNumber: generatedPolicyNumbers.map(
          (policyNumber: { policyNumber: string }) => policyNumber.policyNumber
        ),
      }))

I expected

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
        firstName: 'test',
        lastName: 'test',
        age: 30
        policyNumber: "TRB200",
       }
       {
        firstName: 'test1',
        lastName: 'test1',
        age: 35
        policyNumber: "TRB201",
       }
    {
     firstName: 'test2',
     lastName: 'test2',
     age: 50
     policyNumber: "TRB202",
    }
  ]

But I get

[
    {
        firstName: 'test',
        lastName: 'test',
        age: 30
        policyNumber: [
            "TRB200",
            "TRB201",
            "TRB202"
          ]
       }
       {
        firstName: 'test1',
        lastName: 'test1',
        age: 35
        policyNumber: [
            "TRB200",
            "TRB201",
            "TRB202"
          ]
       }
    {
     firstName: 'test2',
     lastName: 'test2',
     age: 50
     policyNumber: [
        "TRB200",
        "TRB201",
        "TRB202"
      ]
    }
  ]

generatedPolicyNumbers data:

[
  {
    "policyNumber": "TRB200"
  },
  {
    "policyNumber": "TRB201"
  },
  {
    "policyNumber": "TRB202"
  }
]

payload.travelersInfo data:

[
    {
        firstName: 'test',
        lastName: 'test',
        age: 30
       }
       {
        firstName: 'test1',
        lastName: 'test1',
        age: 35
       }
    {
     firstName: 'test2',
     lastName: 'test2',
     age: 50
    }
  ]

>Solution :

Based on the discussion in comments, the solution would be something like this.

  const travelersInfoWithPolicyNumbers = payload.travelersInfo.map((traveler,index) => ({
    ...traveler,
    policyNumber: generatedPolicyNumbers[index].policyNumber,
  }))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading