computed property name js code example

Example 1: Computed Property names

///////////////// COMPUTED PROPERTY NAMES ///////////////////
// allow you to pass in variables for use as property names 
// when initializing an object 
// hit alt / command J and type into console 

// 1. declare a variable = "store a string inside it"

//    variable     string

const myProperty = "string"; 

// 2. then we will declare an object = { and give it a property }
// 3. For this we use our previous myProperty
// declare myObject = { 
[put variable in square braces]: and "give it a value"
}

const myObject = {
[myProperty]: "This is my value"
}

// 4. Now check it look inside myObject
// you can see the proprty identifier was
// created using the string stored in myProperty

// call myObject
type
myObject (hit return result should be..) 

{string: "This is my value"}

// You will sometimes create some code that
// will not know in advance what the property names will be
// and will create them from variables passed to it like this.

Example 2: computed property name javascript

/*
Computed Property Names is ES6 feature which allows 
the names of object properties in JavaScript OBJECT LITERAL NOTATION
to be determined dynamically, i.e. computed.
*/

let propertyname = 'c';

let obj ={
	a : 11,
    b : 12,
    [propertyname] : 13
};

obj; // result is  {a:11 , b:12 , c:13}

//or incase if you want a as your object you can set in this way

let a_value = {
	[obj.a] = obj // a_value's key name as (a) and the complete (obj) present above itself will act as a value
};

Tags:

Misc Example