Skip to content Skip to sidebar Skip to footer

Meaning Of Variable In Array As Property Name?

var expertise = 'journalism' var person = { name: 'Sharon', age: 27, [expertise]: { years: 5, interests: ['international', 'politics', 'internet'] }

Solution 1:

It is syntactic sugar, introduced in ECMAScript 6

Computed property names

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 as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already.

ECMAScript 5

var expertise = 'journalism'var person = {
    name: 'Sharon',
    age: 27
}
person[expertise] = {
    years: 5,
    interests: ['international', 'politics', 'internet']
}

ECMAScript 6

var expertise = 'journalism'var person = {
    name: 'Sharon',
    age: 27,
    [expertise]: {
        years: 5,
        interests: ['international', 'politics', 'internet']
    }
}

Solution 2:

So that, you can refer to the string value stored in the expertise variable, that is, journalism.

var expertise = 'journalism'var person = {
name: 'Sharon',
age: 27,
[expertise]: {
years: 5,
interests: ['international', 'politics', 'internet']
}
}

console.log(person.journalism.years);
console.log(person[expertise].years);

Run this code snippet, and note the two console logs.

Without the brackets, you'd have the string "expertise" instead, as the property name.

You can read more about it here on MDN.

Computed property names

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 as the property name. This is symmetrical to the bracket notation of the property accessor syntax, which you might have used to read and set properties already. Now you can use the same syntax in object literals, too

var param = 'size';
var config = {
  [param]: 12,
  ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
};

console.log(config); // {size: 12, mobileSize: 4}

Solution 3:

It is Computed property (ES2015) :

This is a sample:

var prop = 'foo';
var o = {
  [prop]: 'hey',
  ['b' + 'ar']: 'there'
};

and you may use :

console.log(o.foo)  // hey
console.log(o.bar)  // there

Post a Comment for "Meaning Of Variable In Array As Property Name?"