Skip to content Skip to sidebar Skip to footer

Add Different Value To The Same Object Literal Javascript

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 th

Solution 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) { // columnsvar 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 firstvar 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.

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

Post a Comment for "Add Different Value To The Same Object Literal Javascript"