- How to use a variable for a key in a JavaScript object literal?
- Syntax
- Example
- Using variables as key of JavaScript object
- Using variables as key of JavaScript object
- Using variable keys to access values in JavaScript objects
- 3 Answers 3
- dynamic keys for object literals in Javascript [duplicate]
- 8 Answers 8
- Edit
- JavaScript set object key by variable
- 8 Answers 8
How to use a variable for a key in a JavaScript object literal?
In JavaScript, sometimes, we are required to use the variables as an object key. For example, when fetching data from the API and not sure about all the response data attributes, we must iterate through the response object and store every property of it.
However, we can’t use the variables as a key while creating the object, but after creating, we can add the variable properties to the object.
Syntax
Users can follow the syntax below to use a variable for a key in a JavaScript object.
In the above syntax, ‘key’ is a variable containing some value.
Example
In the example below, we have created the object containing the table properties. Also, we have created the ‘dimensions’ variable to store the table’s dimensions. The ‘key’ variable contains the ‘dimensions’ as a string value.
After creating the object, we used the ‘key’ variable as an object property and the value of the ‘dimension’ variable as an object property value.
Using variables as key of JavaScript object
In the output, users can observe that table dimensions are stored as a value of the ‘dimensions’ object.
In the example below, we have created an empty object. After that, we have used the for loop to make 10 iterations. We use the ‘I’ in every iteration as a key and i*i as a property value.
In this way, we store the square of the number as a value and the number as a key itself.
Using variables as key of JavaScript object
Users learned to use the variable as a key while creating the JavaScript object. When we use the variable as a key, it actually uses the variable’s value as a key.
Using variable keys to access values in JavaScript objects
The problem: alert(data.A5A50000[0].time); properly displays «2009-05-27 16:36:45». alert(bsID); properly displays «A5A50000». alert(data.bsID[0].time); reports «data.bsID is undefined». alert(data[bsID][0].time); reports «data[bsID] is undefined». I’m a little unclear when a variable is/isn’t evaluated. Maybe I’m overlooking something silly, but I can’t figure out my problem here.
alert(bsID) reports «A5A50000». Updated original updateDashboardData() function above. When I initiate the function from the console by updateDashboardData(); I am greeted with: «data[bsID] is undefined 192.168.2.236/michaelg/js/xmonitor.js Line 21». Line 21 is the alert(). Is there anything functionally different between the initial code and how I’m applying it here which might be affecting the outcome?
Yes! Replace this function(data) < With this function() < in the inner each function. you're overriding the value.
3 Answers 3
You can access object properties by dot notation or by bracket notation.
var x = ; alert(x.test); // alerts hi alert(x['test']); // alerts hi
When you have a dynamic value, you have to use the latter:
var property = 'test'; alert(x.property); // looks for x.property, undefined if it doesn't exist alert(x[property]); // looks for x['test'], alerts hi
So what you actually want is:
Not sure what you’re doing wrong, but this is working for me on Firebug’s console:
var data = <"A5A50000":[<"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453>]>; var bsID = 'A5A50000'; alert(data[bsID][0].time);
After attempting your suggestion, alert(data[bsID][0].time); reports «data[bsID] is undefined». I’ve updated the code I’m testing with above. I’m testing this within the console of Firebug (on FF, obviously).
I tried your test code and it, too, worked fine for me. Looking at the code above, the only thing I can imagine going wrong is the bsID is not what was expected. Testing the type of bsID, it reports «string». Further testing suggestions a problem with the data returned from getJSON(). When I attempt to access data[bsID][0] where data is from getJSON, it reports undefined. If I explicitly define data as the object I posted in the orig question, it works. I need to play with the returned data further to see what’s wrong.
dynamic keys for object literals in Javascript [duplicate]
Ok so I’m working away on a project in Nodes, and I’ve come across a small problem with the keys in object literals, I have the following set-up:
Ok so many of you will look at this and think it look’s OK, but the compiler keeps telling me that I am missing a : (colon), which im not, it seems like the + or and the . are both effecting the compiler. Now i believe (not sure), that object literals are created at compile time, and not run-time, meaning that dynamic variables such as this.applicationPath and concatenation are not going to be available 🙁 🙁 What’s the best way to overcome an obstacle like this without having to rewrite large chunks of code.
8 Answers 8
Computed property names are supported in ECMAScript2015:
var name = 'key'; var value = 'value'; var o = < [name]: value >; alert("o as json : " + JSON.stringify(o));
This is a more correct answer, in the sense that it answers the question that was asked better than the accepted answer: the accepted answer deals with bound objects, not object literals / «inline objects».
I remember seeing this years ago and thinking it was unnecessary. It’s actually very useful with Typescript for since it infers the type at object creation implicitly and saves a lot of ugly, explicit boilerplate code.
Prior to ECMAScript 2015 (ed 6), an object literal (ECMAScript calls it an «object initializer») key must be one of:
So you couldn’t use an expression as the key in an initialiser. This was changed as of ECMAScript 2015 (see below). You could use an expression with square bracket notation to access a property, so to set the properties with an expression you had to do:
var required = < directories : <>>; required.directories[this.applicationPath] = "Application " + this.application + " does not exists"; required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists"; .
and so on. Since this.applicationPath is reused a lot, better to store a reference to help with performance and cut down the amount of code:
var a = this.applicationPath; var required = < directories : <>>; var rd = required.directories; rd[a] = "Application " + this.application + " does not exists"; rd[a + "/configs"] = "Application config folder does not exists"; .
Edit
As of ECMAScript 2015 (ed 6), object initializers can have computed keys using:
There is also shorthand syntax for property and method names.
@RobG It is adopted by the US, but it’s not US-centric. It’s also used in the UK; depends on whether you went to Oxford or to Cambridge. The -izer spelling predates the US. You can find more info in the link I posted in my previous comment.
You can set dynamic keys is with bracket notation:
required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";
(of course wherever you do this definition, this.applicationPath must exist)
But do you need this.applicationPath in the keys? How do you access theses values? Maybe you can just remove this.applicationPath from whatever value you use to access the properties.
You could use an array to initialize the keys if you want to avoid repeating a lot of code:
var dirs = ['configs', 'controllers', . ]; var files = ['init.js', 'controllers/index.js', . ]; var required = < directories: <>, files: <> >; required.directories[this.applicationPath] = "Application " + this.application + " does not exists"; for(var i = dirs.length; i--;) < required.directories[this.applicationPath + '/' + dirs[i]] = "Application " + dirs[i] + " folder does not exists"; >for(var i = files.length; i--;) < // same here >
I don’t need them in the key’s, however it was just a preference, ill change it around, your approach seems most reasonable.
Thanks Felix, I went for the «/config» approach as the key, and concatenated in the for loop, there was no reason for me to use the variables in the indexes but it’s just late here, thanks again bud.
Though verbose you can use: < . Object.defineProperty(<>, key, < value, enumerable: true >) > , where key and value are variables spread into in a literal object notation by defining an object with that key and value. Though < Javascript object with variable key: value >would be concise where supported.
Inspired by how babel coverts the new ES6 syntax ( ) to old Javascript, I learned that you can do it with a one liner:
var obj = (_obj = <>, _obj[expression] = value, _obj);
var dynamic_key = "hello"; var value = "world"; var obj = (_obj = <>, _obj[dynamic_key] = value, _obj); console.log(obj); // Object
If you have a deep object structure (such as Grunt config), it’s sometimes convenient to be able to return dynamically-generated object keys using the bracket notation outlined by Felix, but inline within the object structure. This can be achieved by using a function to dynamically return an object within the context of the deep object; in the case for the code in this question, something like this:
var required = < directories : function() < var o = <>; o[this.applicationPath] = "Application " + this.application + " does not exists"; o[this.applicationPath + "/configs"] = "Application config folder does not exists"; o[this.applicationPath + "/controllers"] = "Application controllers folder does not exists"; o[this.applicationPath + "/public"] = "Application public folder does not exists"; o[this.applicationPath + "/views"] = "Application views folder does not exists"; return o; >(), files : function() < var o = <>; o[this.applicationPath + "/init.js"] = "Application init.js file does not exists"; o[this.applicationPath + "/controllers/index.js"] = "Application index.js controller file does not exists"; o[this.applicationPath + "/configs/application.js"] ="Application configs/application.js file does not exists"; o[this.applicationPath + "/configs/server.js"] ="Application configs/server.js file does not exists"; return o; >() >
JavaScript set object key by variable
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount"; myArray.push( < key : someValueArray >);
but when I try to examine my array of objects for every object the key is «key» instead of the value of the variable key. Is there any way to set the value of the key from a variable? Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/
The solution in ES6 is to put the variable in square brackets in order to evaluate it. var key = «happyCount»; myArray.push(< Javascript object with variable key: someValueArray >);
@Jake The only browser that currently does not support this es6 feature is IE11: kangax.github.io/compat-table/es6/…
@Jake Like Hunter says, it’s best not to code for ES5 users. If you need to support older browsers, pollyfill & transpile. It’s now 2018, not 2009, we really need to move on.
8 Answers 8
You need to make the object first, then use [] to set it.
var key = "happyCount"; var obj = <>; objJavascript object with variable key = someValueArray; myArray.push(obj);
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount"; const someValueArray= [. ]; const obj =
@Frank Nocke I’m looking forward to be able to use it in about 10 years time when all the ‘browsers’ we have to support support it.
@Jake you can program in ES6 or ES7 today, and have Babel compile your JS file back to ES5. This is how webapps are built nowadays.
In ES6, you can do like this.
var key = "name"; var person = ; // same as var person = console.log(person); // should print Object
var key = "name"; var person = ; console.log(person); // should print Object
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = <>; yourObject[yourKey] = "yourValue"; console.log(yourObject );
var person = <>; var key = "name"; personJavascript object with variable key /* this is same as person.name */ = "John"; console.log(person); // should print Object
var person = <>; var key = "name"; personJavascript object with variable key /* this is same as person.name */ = "John"; console.log(person); // should print Object