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"}
]
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
M. Leon
  • 11
  • 3

1 Answers1

-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];
  }
}
  • 1
    [Don't use `for…in` enumerations on arrays!](https://stackoverflow.com/q/500504/1048572) – Bergi Jun 19 '17 at 23:20