Skip to content

Instantly share code, notes, and snippets.

@modster
Forked from prof3ssorSt3v3/square-brackets.js
Created April 22, 2023 16:03
Show Gist options
  • Save modster/81f38ac96d3dbe908bda8d9616682f94 to your computer and use it in GitHub Desktop.
Save modster/81f38ac96d3dbe908bda8d9616682f94 to your computer and use it in GitHub Desktop.
/***
* Dynamic Object properties using square brackets
*/
let beverage = 'Beer';
const myObj = {
a: 1,
b: 2,
c: 3,
food: 'cheese',
propName: 'cheese',
beverage: 'Heineken', // beverage: 'Heineken'
[beverage]: 'corona', // Beer: 'corona'
};
let addProp = (obj, propName, propValue) => {
// obj.food = 'cheese';
obj[propName] = propValue;
obj.propName = propValue;
};
addProp(myObj, 'food', 'cheese');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment