4
    var curr = data[i],
        newArray = [],
        key = curr.Frequency.Type,
        obj = {key: []};
    newArray.push(obj);

However, this yields an object with a key of "key"! How can I create a new object with a key of the value of the variable key?

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • 2
    This is a very frequently asked question. – Pointy Sep 04 '13 at 15:28
  • 1
    possible duplicate of [Key for javascript dictionary is not stored as value but as variable name](http://stackoverflow.com/questions/10640159/key-for-javascript-dictionary-is-not-stored-as-value-but-as-variable-name) – Pointy Sep 04 '13 at 15:29
  • 1
    possible duplicate of [How to use a variable as a key inside object initialiser](http://stackoverflow.com/questions/10631007/how-to-use-a-variable-as-a-key-inside-object-initialiser) – zzzzBov Sep 04 '13 at 15:30
  • Here's one that's even older: http://stackoverflow.com/a/15960027/497418 – zzzzBov Sep 04 '13 at 15:38

4 Answers4

2

You can do this:

var curr = data[i],
    newArray = [],
    key = curr.Frequency.Type,
    obj = {};

obj[key] = [];
newArray.push(obj);

There's no way to do it in JavaScript within the object literal itself; the syntax just doesn't provide for that.

edit — when this answer was written, the above was true, but ES2015 provides for dynamic keys in object initializers:

var curr = data[i],
    key = curr.Frequency.Type,
    newArray = [ { [key]: [] } ];
Pointy
  • 405,095
  • 59
  • 585
  • 614
1

I think you mean this notation:

var type = "some type";
var obj = {}; // can't do it one line
obj[type] = [];
console.log(obj); // { "some type": [] }
Halcyon
  • 57,230
  • 10
  • 89
  • 128
1

simply instantiate a new anonymous object from a function.

obj = new function () {
    this[key] = [];
};
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
0

I realise this is an old question but for those finding this through Google the way to do this with ES6+ is to use square bracket notation in the object literal:

const key = 'dynamicKey';
const value = 5;

const objectWithDynamicKey = {
  staticKey: 'another value',
  [key]: value 
}
console.log(objectWithDynamicKey) 

Which prints:

{ 
  staticKey: 'another value', 
  dynamicKey: 5
}

So your example should be:

var curr = data[i];
var newArray = [];
var key = curr.Frequency.Type;
var obj = { [key]: [] };
newArray.push(obj);
sbason
  • 11
  • 2