简体   繁体   English

在同一索引处合并2个多维数组

[英]merging 2 multidimensional arrays at the same index

javascript javascript

I'm trying to either merge 2 multidimensional arrays at the same index or randomize the same index of both arrays the same. 我正在尝试在相同的索引处合并2个多维数组,或者将两个数组的相同索引随机化。

var arr1 = [[a, b, c], [d, e], [f, g, h, i]]
var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]]

preferredResult = [{a: 1, b: 2, c: 3}, {d: 5, e:6}, {f: 7, g: 8, h: 9, i: 10}]

I've tried .maps, nested for loops, .push in different variations and have not been able to figure this out. 我尝试了.maps,嵌套循环,.push的各种变体,但无法弄清楚。

Alternatively, if I could figure out how randomize two arrays of arrays in the same way, that would work as well, ie: the letters in arr1[0] and numbers in arr2[0] could be set to the same randomization, then arr1[1] & arr2[1] and so on. 或者,如果我能弄清楚如何以相同的方式随机化两个数组,那也可以工作,即:可以将arr1 [0]中的字母和arr2 [0]中的数字设置为相同的随机化,那么arr1 [1]和arr2 [1]等。

function merge(arr1, arr2) {
   return arr1.map(function (arr, i) {
      return mergeIntoObject(arr1[i], arr2[i])); 
   };
}

function mergeIntoObject(arr1, arr2) {
  var result = {};
  arr1.forEach((arr, i) => {
    result[arr1[i]] = arr2[i];
  });
  return result;
}

merge(arr1, arr2);

Using embedded for loops 使用嵌入式for循环

 var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]] var result = [] for (let i = 0; i < arr1.length; i++){ let obj = {}; for (let j = 0; j < arr1[i].length; j++){ obj[arr1[i][j]]=arr2[i][j] } result.push(obj); } console.log(result) 

You can use array#map and array#reduce 您可以使用array#maparray#reduce

 const arr1 = [['a', 'b', 'c'], ['d','e' ], ['f', 'g', 'h', 'i']], arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]], result = arr1.map(function(a, i){ return a.reduce(function(r, v, j){ r[v] = arr2[i][j]; return r; }, {}); }); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Lodash can be super helpful. Lodash可能会很有帮助。

 var arr1 = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i']] var arr2 = [[1, 2, 3], [5, 6], [7, 8, 9, 10]] var out = _.zipWith(arr1, arr2, (x,y)=>_.fromPairs(_.zip(x,y))); console.log(out) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

zip will combine 2 arrays into pairs and zipWith will do the same but let you choose how to combine them. zip将2个数组组合成对,而zipWith将做同样的事情,但是让您选择如何组合它们。

Use map & forEach method 使用mapforEach方法

 var arr1 = [ ['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h', 'i'] ], arr2 = [ [1, 2, 3], [5, 6], [7, 8, 9, 10] ], m = arr1.map(function(item, index) { let tempObj = {}; item.forEach(function(item2, index2) { tempObj[item2] = arr2[index][index2]; }); return tempObj; }); console.log(m) 

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

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