Search code examples
javascriptarraysobject-literal

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 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


Solution

  • 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.