将两个数组的值合并为对象 [英] Combine the values of two arrays into object
本文介绍了将两个数组的值合并为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组:
array1 = ["Bob", "John", "Dave"];
array2 = [1, 2, 3];
是否将两者结合成一个包含对象的javascript数组:
Is there combine the two into a javascript array filled with objects that looks like:
[
{meta: 'Bob', value: 1 },
{meta: 'John', value: 2},
{meta: 'Dave', value: 3}
]
推荐答案
这是实现它的方法之一.您可以使用 Array#forEach
函数遍历 array1
中的每个元素.然后,创建一个空对象并设置指定的属性-在您的情况下为 meta
和 value
.然后-给它分配元素,然后将其推入 arr
变量.
It's one of the ways how to achieve it. You can use Array#forEach
function to iterate over every element from array1
. Then, create empty object and set specified properties - in your case: meta
and value
. Then - assign elements to it and just push it into the arr
variable.
var array1 = ["Bob", "John", "Dave"],
array2 = [1, 2, 3],
arr = [];
array1.forEach(function(v,i){
var obj = {};
obj.meta = v;
obj.value = array2[i];
arr.push(obj);
});
console.log(arr);
这篇关于将两个数组的值合并为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文