将数组B中对象的属性传递给数组A.

时间:2017-06-19 22:08:12

标签: javascript arrays properties javascript-objects

假设我们有一个包含许多对象的数组。每个对象都有定义的属性:

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

我们有第二个数组,其中包含arr1中对象的附加属性。 arr2中的对象与arr1:

的顺序相同
{{1}}

有没有办法将arr2中对象的属性插入arr1?

预期结果是

{{1}}

1 个答案:

答案 0 :(得分:-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];
  }
}