如何在JavaScript中将两个数组组合成对象数组? [英] How to combine two arrays into an array of objects in javascript?

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

问题描述

我有两个数组,我想形成一个对象数组,以使obj的新数组具有两个键,第一个键填充有第一个数组的元素,第二个键具有第二个数组的arrays元素。可以使用地图功能完成此操作。我找到了最接近的答案:-
将两个数组合并为具有属性值的对象数组

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. 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

例如:-

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

但是它使用了角度JS,我只想使用纯JS。

But it uses angular JS I just want to use pure 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.

对于您所要解决的任务,是 zip 数组,但是,JS没有内置的 zip 函数,因此我们可以通过 map 函数对其进行仿真:

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:

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]] 
                      });

输出将是:

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

如果要在输出中使用对象(而不是数组),则可以将上面的return语句编辑为类似以下内容:

If you want objects in your output (rather than arrays), you can just edit the return statement above to something like:

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

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

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