Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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.

share|improve this question

marked as duplicate by Boaz, Felix Kling Jul 23 '14 at 0:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1 Answer 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);
share|improve this answer
    
will this value tempObj[columns[i]] be replaced for each iteration? –  Herious 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 –  Herious Jul 23 '14 at 19:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.