简体   繁体   English

如何在javascript中将两个数组组合成一个对象数组?

[英]How to combine two arrays into an array of objects in javascript?

I have two arrays and I want to form an array of objects such that the new array of obj has two keys with first key being filled with elements of first array and second key having arrays elements of second array.我有两个数组,我想形成一个对象数组,这样 obj 的新数组有两个键,第一个键填充第一个数组的元素,第二个键具有第二个数组的数组元素。 Can this be done using the map function.这可以使用地图功能完成。 I found the closest answer as this:- Merge two arrays into an array of objects with property values我找到了最接近的答案:- 将两个数组合并到一个具有属性值的对象数组中

eg.:-例如。:-

ar1=[];
ar2=[];
armixed=[{ar1element,ar2element},{}......]

But it uses angular JS I just want to use pure JS.但它使用 Angular JS 我只想使用纯 JS。

I'm not sure what your output should be but the one you provided seems invalid.我不确定您的输出应该是什么,但您提供的输出似乎无效。 I have modified the output format to be valid.我已将输出格式修改为有效。

For the task you have the solution is to zip the arrays, however, JS has no inbuilt zip function, so we can emulate it via map function:对于您的任务,解决方案是zip数组,但是,JS 没有内置的zip函数,因此我们可以通过map函数模拟它:

var ar1 = ['a1', 'a2', 'a3', 'a4', 'a5'];
var ar2 = ['b1', 'b2', 'b3', 'b4', 'b5'];
var armixed = ar1.map(function (x, i) { 
                          return [x, ar2[i]] 
                      });

Output will be:输出将是:

armixed = [
    ["a1", "b1"]
    ["a2", "b2"]
    ["a3", "b3"]
    ["a4", "b4"]
    ["a5", "b5"]
]

If you want objects in your output (rather than arrays), you can just edit the return statement above to something like:如果您想要输出中的对象(而不是数组),您可以将上面的 return 语句编辑为:

return { categories: x, catid: ar2[i] }

Just to clarify, do you want an object for each unique possible combination of the arrays?只是为了澄清一下,您是否想要一个对象用于数组的每个唯一可能组合? If so, nesting two map functions should do the trick:如果是这样,嵌套两个 map 函数应该可以解决问题:

 let newArray = [{}] arr1.map(i => { arr2.map (j => { newArray.push({prop1: i, prop2: j}) }) })

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

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