0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Casper
  • 1,663
  • 7
  • 35
  • 62

1 Answers1

1

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);
Lochemage
  • 3,974
  • 11
  • 11
  • will this value `tempObj[columns[i]]` be replaced for each iteration? – Casper Jul 23 '14 at 18:29
  • Using the bracket operator on an object is the same as doing something like `tempObj.name = data[i]`, except it allows you to specify the property variable from a string value like 'name'. In the end, using `tempObj['name'] = 'foo'` is exactly the same as using `tempObj.name = 'foo'` – Lochemage Jul 23 '14 at 19:43
  • thanks, but I think my question here is insufficient, I've posted another question [here](http://stackoverflow.com/questions/24919292/add-different-value-to-the-same-object-literal-javascript) – Casper Jul 23 '14 at 19:46