Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square Brackets Javascript Object Key

Can anyone explain how the why/how the below method of assigning keys in JavaScript works?

a = "b"
c = {[a]: "d"}

return:

Object {b: "d"}
like image 816
lcharbon Avatar asked Oct 02 '22 10:10

lcharbon


People also ask

What do square brackets do in JavaScript?

The [] operator converts the expression inside the square brackets to a string. For instance, if it is a numeric value, JavaScript converts it to a string and then uses that string as the property name, similar to the square bracket notation of objects to access their properties.

Which brackets is used to write object in JavaScript?

An object can be created with figure brackets {…} with an optional list of properties. A property is a “key: value” pair, where a key is a string (also called a “property name”), and value can be anything. Let us visualize this with the following syntax for creating an object in JavaScript.

What is bracket notation in JavaScript?

Bracket notation is another way to access a property of an object. To use bracket notation, write the name of the object, followed by brackets [] . Inside the brackets, write the property name as a string. Bracket notation, unlike dot notation, can be used with variables.

What is key value pair in JavaScript?

An object contains properties, or key-value pairs. The desk object above has four properties. Each property has a name, which is also called a key, and a corresponding value. For instance, the key height has the value "4 feet" . Together, the key and value make up a single property.


2 Answers

It's the new ES2015 (the EcmaScript spec formally known as ES6) computed property name syntax. It's a shorthand for the someObject[someKey] assignment that you know from ES3/5:

var a = "b"
var c = {[a]: "d"}

is syntactic sugar for:

var a = "b"
var c = {}
c[a] = "d"
like image 241
Sean Vieira Avatar answered Oct 09 '22 15:10

Sean Vieira


Really the use of [] gives an excellent way to use actual value of variable as key/property while creating JavaScript objects.

I'm pretty much statisfied with the above answer and I appreciate it as it allowed me to write this with a little example.

I've executed the code line by line on Node REPL (Node shell).

> var key = "fullName";     // Assignment
undefined
>
> var obj = {key: "Rishikesh Agrawani"}    // Here key's value will not be used
undefined
> obj     // Inappropriate, which we don't want
{ key: 'Rishikesh Agrawani' }
>
> // Let's fix
undefined
> var obj2 = {[key]: "Rishikesh Agrawani"}
undefined
> obj2
{ fullName: 'Rishikesh Agrawani' }
>
like image 50
hygull Avatar answered Oct 09 '22 16:10

hygull