admin管理员组

文章数量:1395381

    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?

    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?

Share Improve this question asked Sep 4, 2013 at 15:26 benhowdle89benhowdle89 37.5k74 gold badges207 silver badges340 bronze badges 4
  • 2 This is a very frequently asked question. – Pointy Commented Sep 4, 2013 at 15:28
  • 1 possible duplicate of Key for javascript dictionary is not stored as value but as variable name – Pointy Commented Sep 4, 2013 at 15:29
  • 1 possible duplicate of How to use a variable as a key inside object initialiser – zzzzBov Commented Sep 4, 2013 at 15:30
  • Here's one that's even older: stackoverflow./a/15960027/497418 – zzzzBov Commented Sep 4, 2013 at 15:38
Add a ment  | 

4 Answers 4

Reset to default 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]: [] } ];

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": [] }

simply instantiate a new anonymous object from a function.

obj = new function () {
    this[key] = [];
};

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);

本文标签: JavaScript set anonymous Object key to variable nameStack Overflow