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

[
    {
        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,
  }))

Leave a Reply