不同的价值添加到同一个对象的JavaScript字面 [英] Add different value to the same object literal javascript
问题描述
我有一块code来创建一个对象字面数组。该阵列由2其他字符串数组创建的,一会成为对象文本 colHeads
和其他阵列将数据 dataArr
。
I have a piece of code to create an object literal array. The array is created from 2 other string array, one will become the object literal colHeads
and the other array will be the data dataArr
.
colHeads = [名称,状态]
dataArr = [约翰·A·史密斯,琼·琼斯]
var temp = [];
var tempObj = {};
for (var i=0; i<colHeads.length; ++i) { // columns
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[i]] = dataArr[j];
}
temp.push(tempObj);
}
最后阵列应该是这样的:
The final array should look like this:
var data = [
{name: 'John A. Smith', state: 'CA'},
{name: 'Joan B. Jones', state: 'NY'}
];
下面的问题是根据该行 TEMPOBJ [colHeads [I] = dataArr [0];
对象常量会在两个数组中的最后一项更换的使结果是这样的:
Problem here is according to this line tempObj[colHeads[i]] = dataArr[0];
The object literal would be replaced with the last entry in both arrays which make the result look like this:
var data = [
{name: 'Joan B. Jones', state: 'NY'},
{name: 'Joan B. Jones', state: 'NY'}
];
我是新来的JavaScript,所以我不知道很多语法
I'm new to javascript so I don't know much the syntax
推荐答案
首先,你的循环访问相同dataArr指数,它应该使用Ĵ
First off, your loop is accessing the same dataArr index, it should be using j
tempObj[colHeads[i]] = dataArr[j];
二,你是不是建设新tempObjs每个回路,所以每个项目指标股同样TEMPOBJ这将最终让你有完全相同的对象列表。
Second, you are not constructing new tempObjs for each loop, so each item index shares the same tempObj which will end up leaving you with a list of the same exact object.
到目前为止,您的code看起来应该是这样的东西更多:
So far your code should look something more like this:
var temp = [];
for (var i=0; i<colHeads.length; ++i) { // columns
var tempObj = {};
var dataArr = colDatas[i].split(",");
for (var j = 0; j < dataArr.length; j++) { // data
tempObj[colHeads[j]] = dataArr[j];
}
temp.push(tempObj);
}
最后,我们会根据每列制作一个TEMPOBJ,而不是每一行,你应该做的。
Lastly, You are only creating one tempObj for each column, rather than each row as you should be doing.
var temp = [];
var rowCount = colDatas[0].split(',').length;
for (var i = 0; i < rowCount; ++i) { // rows first
var tempObj = {};
for (var j = 0; j < colHeads.length; ++j) { // now columns
tempObj[colheads[j]] = colDatas[j].split(',')[i];
}
temp.push(tempObj);
}
现在,由于设置你的colDatas对象的方式,它要求你将它们分割为每循环,可以成为pretty昂贵的,我建议你找到另一种方式来存储它们,让它们能够更好的优化。
Now, due to the way your colDatas object is set up, it requires you to split them for every loop which can become pretty costly, I suggest you find another way to store that so it can be better optimized.
这篇关于不同的价值添加到同一个对象的JavaScript字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!