简体   繁体   English

将两个多维数组合并为带有对象的多维数组

[英]Merging two Multidimensional Arrays into a Multidimensional Array with Objects

I'm learning the new JavaScript ES6 syntax and am trying to create a multidimensional array with objects from 2 other multidimensional arrays. 我正在学习新的JavaScript ES6语法,并尝试使用其他2个多维数组中的对象创建一个多维数组。 Presumably my syntax is incorrect, but I don't know how to fix it. 大概我的语法不正确,但是我不知道如何解决它。 The result should be: 结果应为:

[
  [{    letter: w,    instances: 1
  }, {  letter: o,    instances: 1
  }, {  letter: d,    instances: 2
  }, {  letter: r,    instances: 1
  }],
  [{    letter: s,    instances: 1
  }, {  letter: y,    instances: 1
  }],
  [{    letter: h,    instances: 1
  }, {  letter: e,    instances: 1
  }, {  letter: l,    instances: 2
  }, {  letter: o,    instances: 1
  }]
]

My code uses two map methods: 我的代码使用两种映射方法:

 var letters = [ ["w", "o", "d", "r"], ["s", "y"], ["h", "e", "l", "o"] ]; var numbers = [ [1, 1, 2, 1], [1, 1][1, 1, 2, 1] ]; var objArr = letters.map(function(c, i) { return c.map(function(c2, i2, a2) { return { letter: c2, instances: numbers[i] } }) }); console.log(objArr); 

It correctly returns a multidimensional array with objects and correct letter values, but the number values are incorrect. 它可以正确返回带有对象和正确字母值的多维数组,但是数字值不正确。 Can anyone find why this happens? 有人能找到原因吗? Also, does anyone think there's a better way of storing the letters and the number of numbers? 另外,有人认为还有更好的方法来存储字母和数字数量吗?

One very small mistake in instances: Pls see below instances:一个非常小的错误instances:请参见下文

 var letters = [["w", "o", "d", "r"],["s", "y"],["h", "e", "l", "o"]]; var numbers = [[1,1,2,1],[1,1], [1,1,2,1]]; var objArr = letters.map(function(c,i) { return c.map(function(c2,i2) { return {letter: c2, instances: numbers[i][i2]} }) }); console.log(objArr) 

Since you have a two-dimensional array, you need to use two indexes to access it. 由于您有一个二维数组,因此需要使用两个索引来访问它。 Use the first index i , to access the inner array and the use second index j , to access the number inside the array. 使用第一个索引i来访问内部数组,使用第二个索引j来访问数组内部的数字。

 let letters = [["w", "o", "d", "r"],["s", "y"],["h", "e", "l", "o"]], numbers = [[1, 1, 2, 1],[1, 1],[1, 1, 2, 1]], result = letters.map((arr, i) => arr.map((letter, j) => ({letter,instances: numbers[i][j]}))); console.log(result); 

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

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