Add different value to the same object literal javascript

自古美人都是妖i 提交于 2019-12-12 02:06:31

问题


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 = [name, state]

dataArr = [John A. Smith,Joan B. Jones]

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'}
    ];

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'}
    ];

I'm new to javascript so I don't know much the syntax


回答1:


First off, your loop is accessing the same dataArr index, it should be using j

tempObj[colHeads[i]] = dataArr[j];

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.

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);
}

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);
}

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.




回答2:


Create new object in cycle (prepare arrays before it), like this:

for (var i=0; i<colHeads.length; ++i) {
    var tmpObj = {};
    tmpObj.name = colHeads[i];
    tmpObj.state = colDatas[i]
    result.push(tmpObj);
}


来源:https://stackoverflow.com/questions/24919292/add-different-value-to-the-same-object-literal-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!