Reputation: 201
iam trying to set a variable as a keyname but as always iam just failing. (javascript newbie)
Here is my example object:
disk = {
"id": {
"type": "xxxx",
"content": "xxxx"
}
}
Later i want to output my content with disk[id].content. Now the question is how to set the key 'id' with an variable? (got a unique id with i try to get in there)
In the end it should read: (for example) disk = { "5546": { "type": "xxxx", "content": "xxxx" } }
Thanks a lot for your help!
Upvotes: 0
Views: 67
Reputation: 57719
So you want:
var id = "5546";
var disk = {
id: {/*etc*/}
}
And expect:
disk: { 5546: {/*etc*/} }
You can't do this in JavaScript with this notation.
You can do:
var id = "5549";
var disk = {};
disk[id] = {/*etc*/};
Upvotes: 2
Reputation: 239291
You can't use variables for key names using object literal notation.
You need to use disk = {}; disk[id] = { content: ..., type: ... }
.
Upvotes: 6