【问题标题】:Javascript: How Do you Combine Two Objects Into One [duplicate]Javascript:如何将两个对象合并为一个 [重复]
【发布时间】:2020-05-16 14:08:27
【问题描述】:

我正在尝试使用 Javascript 或 Jquery 组合两个对象数组,但结果并不符合我的预期。这些是我的数组对象结果:

Arry1 结果:[{"name": "2412"}, {"name": "3324"}, {"name": "8875"}]

Arry2 结果:[{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}]

这就是我所做的将一个推入另一个:

Array.prototype.push.apply(Arry1,Arry2);

问题是上面的代码将它们堆叠在一起。我想得到的对象结构如下:

[ 
{
 "name": "2412",
 "zip": "12051"
},
{
 "name": "3324",
 "zip": "54021"
},
{
"name": "8875",
 "zip": "24521"
}
]

【问题讨论】:

  • 您似乎想“压缩”两个数组中的对象。 Arry1.map((obj, index) => ({ ...obj, ...Arry2[index] }))?
  • 如果其中一个数组有同名的属性会怎样?
  • result = Arry1.map((v, i) => Object.assign({}, v, Arry2[i]));

标签: javascript jquery


【解决方案1】:

通过克隆和结合Object.assign将数组相互映射

let a1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];

let a2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];

let result = a1.map((props, index) => Object.assign(props, a2[index]));

console.log(result);

根据评论编辑:

如果这是一个您将经常与可变数量的数组一起使用的实用程序,您可以考虑创建一个处理它的函数。

    let a1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}],
    a2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}],
    a3 = [{"phone": "1234"},{"phone": "3121"},{"phone": "2136"}];


function combine(first, ...arrs) {
  let result = first.map((props, index) => {
    let combined = [props];
    arrs.forEach(arr => combined.push(arr[index]));
    return Object.assign(...combined);
  })
  return result;
};


let result = combine(a1, a2, a3);
console.log(result);

【讨论】:

  • 这也适用于 3 个对象数组吗?
  • @Zeusox 我更新了我的答案以涵盖这一点。
【解决方案2】:

你可以使用map:

const arr1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];

const arr2 =  [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];

let result = arr1.map((obj, idx) => {
      obj.zip = arr2[idx].zip; 
      return obj
  });

console.log(result)

【讨论】:

    【解决方案3】:

    有多种方法可以做到这一点。以下是其中之一,

    let array1 = [{"name": "2412"}, {"name": "3324"}, {"name": "8875"}];
    let array2 = [{"zip": "12051"}, {"zip": "54021"}, {"zip": "24521"}];
    let resultArray = [];
    for(let i=0; i< array1.length; i++) { // we can consider any of array1 or array 2 length
      resultArray.push({...array1[i], ...array2[i]});
    }
    console.log(resultArray);

    使用 Jquery,我们可以像下面这样,

    let array1 = [{ name: "2412" }, { name: "3324" }, { name: "8875" }];
    let array2 = [{ zip: "12051" }, { zip: "54021" }, { zip: "24521" }];
    
    let resultArray = [];
    $.each(array1, function(index, value) {
       resultArray.push($.extend(value, array2[index]));
    });
    console.log(resultArray);
    

    【讨论】:

    • 这也适用于 3 个对象数组吗?
    • 是的,我们必须改变 push 语句,比如 resultArray.push({...array1[i], ...array2[i], ...array3[i]});
    猜你喜欢
    • 2018-10-15
    • 2013-05-27
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    相关资源
    最近更新 更多