1

Lets say we have one array with a number of objects in it. Each object has defined properties:

arr1 = [
    {name: "Harry", lastname: "Potter"},
    {name: "Charlie", lastname: "Brown"},
    {name: "Frodo", lastname: "Baggins"}
]

We have a second array with an additional properties for the objects in arr1. The objects in arr2 are in the same order as arr1:

arr2 = [
    {bestfriend: "Ron"},
    {bestfriend: "Snoopy"},
    {bestfriend: "Sam"}
]

Is there any way to insert the properties of objects in arr2 to arr1?

The expected result is

arr1 = [
    {name: "Harry", lastname: "Potter", bestfriend: "Ron"},
    {name: "Charlie", lastname: "Brown", bestfriend: "Snoopy"},
    {name: "Frodo", lastname: "Baggins", bestfriend: "Sam"}
]
3
  • Possible duplicate of Javascript Array Map 2D array Commented Jun 19, 2017 at 22:09
  • Yes there is, for instance a simple for loop will do it. You're supposed to do research before asking here. Commented Jun 19, 2017 at 22:12
  • Try: arr1.forEach((o, i) => Object.assign(o, arr2[i])); Commented Jun 19, 2017 at 22:17

1 Answer 1

-1
arr1 = [{name: "Harry", lastname: "Potter"}, {name: "Charlie", lastname: "Brown"}, {name: "Frodo", lastname: "Baggins"}];
arr2 = [{bestfriend: "Ron"}, {bestfriend: "Snoopy"}, {bestfriend: "Sam"}];
for (var i=0; i < arr2.length; i++) {
  for (var prop in arr2[i]) {
    arr1[i][prop] = arr2[i][prop];
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.