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.

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

will this value tempObj[columns[i]] be replaced for each iteration?
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'
thanks, but I think my question here is insufficient, I've posted another question here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.