[javascript] Creating object with dynamic keys

First off, I'm using Cheerio for some DOM access and parsing with Node.js. Good times.

Heres the situation:

I have a function that I need to create an object. That object uses variables for both its keys and values, and then return that single object. Example:

stuff = function (thing, callback) {
  var inputs  = $('div.quantity > input').map(function(){
    var key   = this.attr('name')
     ,  value = this.attr('value');

     return { key : value }
  }) 

  callback(null, inputs);
}

It outputs this:

[ { key: '1' }, { key: '1' } ]

(.map() returns an array of objects fyi)

I need key to actually be the string from this.attr('name').

Whats the best way to assign a string as a key in Javascript, considering what I'm trying to do?

This question is related to javascript object

The answer is


You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).