This question already has an answer here:
这个问题在这里已有答案:
- Creating object with dynamic keys [duplicate] 2 answers
- 用动态键创建对象[重复] 2个答案
- How to create an object property from a variable value in JavaScript? [duplicate] 9 answers
- 如何在JavaScript中从变量值创建对象属性? [重复] 9个答案
I want to create an object literal array like this
我想创建一个像这样的对象文字数组
var data = [
{name: 'John A. Smith', state: 'CA'},
{name: 'Joan B. Jones', state: 'NY'}
];
name
and state
are stored in an array columns
.
名称和状态存储在数组列中。
John A. Smith
and CA
are stored in array data
.
John A. Smith和CA存储在数组数据中。
I'm trying to write this way, but it seemed like I couldn't use the columns[i]
before the :
,
我试着用这种方式写,但似乎我不能在:之前使用列[i]:
var temp = [];
for (var i = 0; i < data.length; i++) {
temp.push({
columns[i]: data[i]
});
}
Thanks Lochemage, it works for my columns. Here is my entire code:
谢谢Lochemage,它适用于我的专栏。这是我的整个代码:
var temp = [];
var tempObj = {};
for (var i=0; i<colHeads.length; i++) { // columns
var dataArr = '$colData.get(i)'.split(",");
for (var j = 0; j < dataArr.length; ++j) { // data
tempObj[colHeads[i]] = dataArr[j];
}
temp.push(tempObj);
}
This '$colData.get(i)'
seems to work with direct index (0, 1, ..), but it won't work with i
.
这个'$ colData.get(i)'似乎适用于直接索引(0,1,...),但它不能用于i。
By the way, $colData
is a string array from velocity markup; it contains strings. In this particular problem, it contains
顺便说一句,$ colData是来自速度标记的字符串数组;它包含字符串。在这个特殊的问题中,它包含
[0]: CA, NY
[1]: John A. Smith, Joan B. Jones
And I need the final result is to be the data
array stated at the top.
我需要最终的结果是在顶部说明的数据数组。
1 个解决方案
#1
1
You have to use the bracket operator with your columns value instead:
您必须将支架运算符与列值一起使用:
var temp = [];
var tempObj = {};
for (var i = 0; i < data.length; ++i) {
tempObj[columns[i]] = data[i];
}
temp.push(tempObj);
#1
1
You have to use the bracket operator with your columns value instead:
您必须将支架运算符与列值一起使用:
var temp = [];
var tempObj = {};
for (var i = 0; i < data.length; ++i) {
tempObj[columns[i]] = data[i];
}
temp.push(tempObj);