Search code examples
javascriptarraysobjectobject-literal

How to use two arrays to create an object literal array in JavaScript


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.

I'm trying to write this way, but it seemed like I couldn't use the columns[i] before the :,

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:

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.

By the way, $colData is a string array from velocity markup; it contains strings. In this particular problem, it contains

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


Solution

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