-1

I have an array of objects. Here is the array:

arr =  [
    {
        "id": 0,
        "name": John,
    },
    {
        "id": 1,
        "name": Kim,
    },
    {
        "id": 2,
        "name": Steven,
    },
]

I want to add another array of objects. Here is the array

arr2 = [
    {
        "surname": "Lewis"
    },
    {
        "surname": "Pitt"
    },
    {
        "surname": "Watson"
    }
]

And I want to get an array like this:

newArr =  [
    {
        "id": 0,
        "name": John,
        "surname": "Lewis",
    },
    {
        "id": 1,
        "name": Kim,
        "surname": "Pitt"
    },
    {
        "id": 2,
        "name": Steven,
        "surname": "Watson"
    },
]

Here is my attempt which gives wrong result:

let newArr = [...arr, arr2.map(({ surname }: any) => ({ surname: surname }))];

I get it:

newArr =  [
    {
        "id": 0,
        "name": John,
    },
    {
        "id": 1,
        "name": Kim,
    },
    {
        "id": 2,
        "name": Steven,
    },
    [
      {
        "surname": "Lewis"
      },
      {
        "surname": "Pitt"
      },
      {
        "surname": "Watson"
      }
    ]
]

I hope for your help. I'm new to this field, so I may not see the obvious things.

Gi S
  • 31
  • 3
  • Use the index in the mapping callback to reference the associated element in the other array, so that you can reference them together in a single object – CertainPerformance Oct 22 '22 at 16:04

1 Answers1

1

const arr = [{
    "id": 0,
    "name": 'John',
  },
  {
    "id": 1,
    "name": 'Kim',
  },
  {
    "id": 2,
    "name": 'Steven',
  },
]

const arr2 = [{
    "surname": "Lewis"
  },
  {
    "surname": "Pitt"
  },
  {
    "surname": "Watson"
  }
]

// create a new array
// for every item in the `arr` create a new item
// that is a combination of properties of that item
// and item in `arr2` at the same index
const newArray = arr.map((e, i) => ({ ...e, ...arr2[i] }))

console.log(newArray)
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Oct 22 '22 at 16:06