循环从2D数组中在Javascript中创建对象键和值 [英] Looping to create object Keys and Values in Javascript from 2D arrays
问题描述
我有两个数组,一个用于保存键,另一个用于保存数组,每个数组包含值。我想创建一个对象数组,其中每个对象都对键和值进行配对。为此,我创建了一个数组,现在我尝试在将对象推入数组之前创建并填充对象。我的代码与此类似:
I have two arrays, one which holds the keys and one which holds arrays, each array containing values. I would like to make an array of objects, where each object pairs the keys and values. To do this, I created an array, and I am now trying to create and fill objects before pushing them into the array. My code looks similar to this:
var keys = [key1, key2, key3];
var values = [
[A-value1, A-value2, A-value3],
[B-value1, B-value2, B-value3],
[C-value1, C-value2, C-value3]
];
var arrayOfObjecs = [];
for(var i=0; i<values.length; i++){
var obj = {
for(var j=0; j<values[i].length; j++){
keys[j] : values[i][j];
}
};
arrayOfObjects.push(obj);
}
最后,我希望我的arrayOfObjects看起来像这样: / p>
In the end, I would like for my arrayOfObjects to look like this:
var arrayOfObjects = [
{
key1 : A-value1,
key2 : A-value2,
key3 : A-value3
},
{
key1 : B-value1,
key2 : B-value2,
key3 : B-value3
},
{
key1 : C-value1,
key2 : C-value2,
key3 : C-value3
}
];
这个问题类似于我想做的事情,但它不允许我在第二次循环对象。
This question is similar to what I want to do, yet it won't allow me to loop a second time within the object.
推荐答案
您的问题实际上是关于对象属性方括号表示法:
using object [ propertyname]与using object相同。 propertyname 。
Your question is in fact about the object properties square bracket notation :
using object[propertyname] is the same as using object.propertyname.
var myObj = {};
myObj['x'] = 12;
console.log(myObj.x); -->> prints 12
现在在您的代码中:
var arrayOfObjects = [];
for(var i=0; i<values.length; i++){
var obj = {};
for(var j=0; j<values[i].length; j++){
obj[keys[j]] = values[i][j];
}
arrayOfObjects.push(obj);
}
回复'它确实奇怪的事情':此代码有效。
In reply to 'it does weird things' : this code works.
使用此输入:
var keys = ['key1', 'key2', 'key3'];
var values = [
[12,112, 1112],
[31, 331, 3331],
[64, 65, 66]
];
输出为:
{ {key1: 12, key2: 112, key3: 1112},
{key1: 31, key2: 331, key3: 3331},
{key1: 64, key2: 65, key3: 66} }
小提琴在这里:
http://jsfiddle.net/fyt8A/
这篇关于循环从2D数组中在Javascript中创建对象键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!