Dan
Dan

Reputation: 2344

Creating a Javascript object array on the fly

Ideally I would like to create an object array in JavaScript like this:

var items = [
  ['test', 2],
  ['test1', 4],
  ['test2', 6]
];

    var test_1 = {};

    for(var i = 0; i < items.length; i++) {

        test_1.items[i][0] = items[i][1];
    }

So, once done I'd like to be able to call

test_1.test which would equal 2.

Is this doable?

Upvotes: 0

Views: 3611

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You need the bracket notation as property accessor

object.property     // dot notation
object["property"]  // bracket notation

var items = [
  ['test', 2],
  ['test1', 4],
  ['test2', 6]
];

var test_1 = {};

for (var i = 0; i < items.length; i++) {
    test_1[items[i][0]] = items[i][1];
    //    ^           ^
}

console.log(test_1);

Upvotes: 3

Related Questions