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
?
- 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
4 Answers
Reset to default 2You 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
版权声明:本文标题:JavaScript set anonymous Object key to variable name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744677794a2619218.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论