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

1
  • 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 Commented Oct 22, 2022 at 16:04

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.