5
    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?

4

4 Answers 4

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]: [] } ];
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

simply instantiate a new anonymous object from a function.

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.