JS Computed Properties

PHOTO EMBED

Wed Jun 29 2022 19:13:46 GMT+0000 (Coordinated Universal Time)

Saved by @Polly

let fruit = 'apple';
let bag = {
  [fruit + 'Computers']: 5 // bag.appleComputers = 5
};

#equivelant to
let fruit = "apple"
let bag = {};

// take property name from the fruit variable
bag[fruit + 'Computers'] = 5; // apple = 5

*****
let propVariableName = 'nominalName' // expression
const data = {
  a: 1,
  [propVariableName]: 2 // assign nominalName as computed property
}
// use value of expression's computed property
data.nominalName // #-> 2 

******
let propVariableNames = [ {'nominalName1: 1'}, {'nominalName2': 2}, {'nominalName3': 3}]
 
// iterate propVariableNames
let data = { }
data[propVariableName]: propVariableName.getValue()


content_copyCOPY

Square Bracket notation for Objects - object properties can have a key + someVariableValue OR + 'string' OR + someArr[idx] - use an expression in [brackets] as a property(key) of object - create a new object dynamically with data driven values [https://www.javascripttutorial.net/es6/javascript-computed-property/]

https://javascript.info/object