[英]Combine the values of two arrays into object
I have two arrays:我有两个数组:
array1 = ["Bob", "John", "Dave"];
array2 = [1, 2, 3];
Is there combine the two into a javascript array filled with objects that looks like:是否将两者组合成一个 javascript 数组,其中填充了如下所示的对象:
[
{meta: 'Bob', value: 1 },
{meta: 'John', value: 2},
{meta: 'Dave', value: 3}
]
Let's break it down.让我们分解一下。
You have two arrays of equal length and you want to extract a value from each.你有两个长度相等的数组,你想从每个数组中提取一个值。
// Could also do array2.length since they're the same size
for (var i = 0; i < array1.length; i++) {
var val1 = array1[i];
var val2 = array2[i]
}
and you want to create an object using those two values并且您想使用这两个值创建一个对象
for (var i = 0; i < array1.length; i++) {
var val1 = array1[i];
var val2 = array2[i]
var obj = {
meta: val1,
value: val2
};
}
Finally, you want to store each of those generated objects in an array最后,您希望将每个生成的对象存储在一个数组中
var result = [];
for (var i = 0; i < array1.length; i++) {
var val1 = array1[i];
var val2 = array2[i]
var obj = {
meta: val1,
value: val2
};
result.push(obj);
}
And now you have your result!现在你有你的结果了!
You could rewrite this in a number of ways.您可以通过多种方式重写它。 For example:
例如:
var result = array1.map(function(val1, index) {
return {
meta: val1,
value: array2[index]
};
});
or if you're in an environment which supports it:或者,如果您处于支持它的环境中:
let result = array1.map((val1, index) => (
{
meta: val1,
value: array2[index]
}
));
It's one of the ways how to achieve it.这是实现它的方法之一。 You can use
Array#forEach
function to iterate over every element from array1
.您可以使用
Array#forEach
函数遍历array1
中的每个元素。 Then, create empty object and set specified properties - in your case: meta
and value
.然后,创建空对象并设置指定的属性 - 在您的情况下:
meta
和value
。 Then - assign elements to it and just push it into the arr
variable.然后 - 为其分配元素并将其推入
arr
变量。
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);
Simple solution using Array.prototype.map()
function:使用
Array.prototype.map()
函数的简单解决方案:
var array1 = ["Bob", "John", "Dave"], array2 = [1, 2, 3], combined = array1.map(function(v, k, a){ return {meta: v, value: array2[k]}; }); console.log(combined);
You could use an object and iterate the keys and the values.您可以使用一个对象并迭代键和值。
var array1 = ["Bob", "John", "Dave"], array2 = [1, 2, 3], object = { meta: array1, value: array2 }, result = Object.keys(object).reduce(function (r, k) { object[k].forEach(function (a, i) { r[i] = r[i] || {}; r[i][k] = a; }); return r; }, []); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
假设您使用的是 Chrome,您可以执行以下操作:
const combined = array1.map((name,i) => ({meta: name, value: array2[i]}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.