Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i name object "keys" programmatically in JavaScript?

What i want is something i do every day in Python. In JS it does not work, most probably because i suck in JS.

This is the Python code that would do what i want:

>key = 'just_a_key'
>value = 5
>dict = {key: value}
>dict
{'just_a_key':5}
>dict['just_a_key'}
5

This does not work in JS, the key there will be just named 'key'. I know this is because i'm not really creating a dictionary here, but using json to create an object when i write the same code. So my question now is: How can i programmatically name the objects "keys" (or properties?) in JS?

like image 745
marue Avatar asked May 17 '12 17:05

marue


People also ask

Can you rename a key in an object JavaScript?

To rename a key in an object:Use bracket notation to assign the value of the old key to the new key. Use the delete operator to delete the old key. The object will contain only the key with the new name.

How do you use a variable name as a key in an object JavaScript?

Syntax: var key="your_choice"; var object = {}; object[key] = "your_choice"; console. log(object);

How are JavaScript object Keys ordered?

To illustrate that JavaScript object keys are not ordered, let's compare them to an array: a simple list of items in a specific order. JavaScript arrays have a defined order from index 0 to the last item in the list, and items added to the array using . push() stay in the order they are added in.

How do I find the key name of an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.

Can objects be keys in JavaScript?

Can you use objects as Object keys in JavaScript? # The short answer is "no". All JavaScript object keys are strings.


2 Answers

Like this:

dict = {};

dict[key] = value;

JavaScript does not evaluate expressions for property names in its object literal notation, but it does if you use the square bracket form of the object member operator.

MDN Member Operators

like image 184
cliffs of insanity Avatar answered Oct 30 '22 16:10

cliffs of insanity


Update: this answer was originally written in 2012, but there's a better way now using ES2015/ES6 Computed Property Names. The previous example (see below) could now be written as follows:

const key = 'just_a_key';

const obj = { [key]: 5 };

If you're unfamiliar with object-literal syntax in JavaScript, please note that the important aspect here is the brackets around the dynamic key name (i.e., [key]). The brackets indicate that key (or any other contents) should be interpreted as an expression, rather than being used as a literal value.


Original answer / pre-ES6 solution:

var obj = {},
    key = 'just_a_key';

obj[key] = 5;
like image 26
jmar777 Avatar answered Oct 30 '22 17:10

jmar777