如何在JavaScript中按索引合并两个对象数组? [英] How can I merge two object arrays by index in JavaScript?

查看:60
本文介绍了如何在JavaScript中按索引合并两个对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下两个数组组合以获得所需结果的最佳方法是什么?我希望将它们按索引进行组合.

What would be the best way to combine the two arrays below to get the desired result. I would want them to be combined by index.

输入为:

var array1 = [[1,2,3,4],[4,5,6,7]]
var array2 = [[a,b,c,d],[e,f,g,h]]

所需的输出为:

var array3 =[{
              array1:[1,2,3,4],
              array2:[a,b,c,d]
             },
             {
              array1:[4,5,6,7],
              array2:[a,b,c,d]
             }]

只要按索引分组,输出的任何变体都将起作用.预先感谢.

Any variation of the output would work as long as they are grouped by indexes. Thanks in advance.

不是建议的重复项.建议[a,1,b,2],但未按所需输出的显示方式进行分组.

not a duplicate of what was suggestion. Suggestion out [a,1,b,2] and does not group the way the desired output shows.

推荐答案

这与如何在JavaScript中压缩两个数组非常相似?,只是将输出格式从数组更改为对象:

This is very similar to How do I zip two arrays in JavaScript?, except you just change the output format from an array to an object:

var array1 = [[1,2,3,4],[4,5,6,7]];
var array2 = [['a','b','c','d'],['e','f','g','h']];

var array3 = array1.map(function(_, i) {
  return {
    array1: array1[i],
    array2: array2[i]
  };
});

console.log(array3);

这篇关于如何在JavaScript中按索引合并两个对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆