简体   繁体   English

在JavaScript中,如何合并一个对象数组和另一个对象数组?

[英]In JavaScript, how do I merge an array of objects with another array of objects?

In a loop, I am trying to merge the contents of two arrays: 在一个循环中,我试图合并两个数组的内容:

var myArray = [{a:"a"},{b:"b"}];//first pass in loop
var myArray = [{c:"c"},{d:"d"}];//second pass in loop

For the result, I would like to have this: 为了达到这个目的,我想要这样:

results = [{a:"a"},{b:"b"},{c:"c"},{d:"d"}];

If I do this at each pass: 如果我每次都这样做:

results.splice(0,0,array[i]);

Then the results array becomes a collection of two arrays, rather than a collection of four objects. 然后, results数组将成为两个数组的集合,而不是四个对象的集合。

I have tried .concat , but that didn't work. 我已经尝试过.concat ,但是没有用。

Is there a way to merge the objects comprising an object array with another object array without using a combination of for() and push() ? 有没有一种方法可以将组成对象数组的对象与另一个对象数组合并,而无需使用for()push()

There must be something simple I have missed. 我一定错过了一些简单的事情。

Thanks 谢谢

actually concat is the right way to go in your example you are defining myarray twice. 实际上,concat是正确的方法,在您的示例中,您两次定义了myarray。 hopefully this is not the case in your code. 希望这不是您的代码中的情况。 when I try 当我尝试

var myArray1 = [{a:"a"},{b:"b"}];
var myArray2 = [{c:"c"},{d:"d"}];
var result = myarray1.concat(myarray2);

This must work. 这必须工作。 if not then please show us the result of these threee lines in your browser 如果不是,请在您的浏览器中向我们显示这三个行的结果

Moataz has your answer, but you mention a loop so you might be looking for: Moataz有您的答案,但您提到了一个循环,因此您可能正在寻找:

var result = [];
var myArray;

for (...) {
  myArray = /* getMyArray()? */
  result = result.concat(myArray);
}

where myArray is set to new values each time. 每次将myArray设置为新值。 You could remove one line by having the logic that assigns the array to myArray in the concat expression. 您可以通过在concat表达式中使用将数组分配给myArray的逻辑来删除一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM