Skip to content
Advertisement

JavaScript set anonymous Object key to variable name

    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?

Advertisement

Answer

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]: [] } ];
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement