Explain Codes LogoExplain Codes Logo

How To Set A JS object property name from a variable

javascript
prompt-engineering
functions
promises
Nikita BarsukovbyNikita Barsukov·Feb 21, 2025
TLDR

To dynamically set an object property in JavaScript, utilize the bracket notation ([]) with a variable in this manner:

let key = "age"; let obj = {}; obj[key] = 30; // Setting the "age" property console.log(obj); // Output: { age: 30 }

Here, obj[key] conveniently creates the age property on obj, crediting it the value 30.

Main Practices and Pitfalls

Assigning Multiple Properties

Let's talk about dynamically assigning multiple properties using a for-loop. Browse through:

let obj = {}; for (let i = 0; i < 5; i++) { obj['key' + i] = `value${i}`; // Adding properties in style } console.log(obj); // Output: { key0: 'value0', key1: 'value1', ... }

Variable Scopes

Now let's tackle variable scopes. Sometimes variables are a scope unto themselves - they can easily deceive you:

function createDynamicObject() { let obj = {}; for (let i = 0; i < 3; i++) { obj['prop' + i] = i; // Invoking variable "i" } return obj; } console.log(createDynamicObject()); // Output: { prop0: 0, prop1: 1, prop2: 2 }

Special Characters

Coding in style includes the use of special characters and expressions in your property names. On the runway:

let specialKey = "This is a *special* property"; // Gotta have style let obj = { [specialKey]: "Special value" // Making it count }; console.log(obj[specialKey]); // Output: "Special value"

ES6: Conciseness is the Key

This looks great, but with ES6, we can make it cooler with concise computed property names:

let prefix = 'data'; let obj = { [`${prefix}Key`]: "some value" // ES6 dazzles! }; console.log(obj.dataKey); // Output: "some value"

Going the Extra Mile

Assign Dynamic Property during Initialization

With ES6, you can make object initialization look like a magic show:

const dynamicKey = 'id'; const dynamicValue = 42; const dynamicObj = { [dynamicKey]: dynamicValue // The magic happens here }; console.log(dynamicObj.id); // Output: 42

Variables in Nested Scopes

For those who love closures, just be cautious about overwriting variables:

function createCounter() { let count = 0; return function() { let propName = `count${++count}`; this[propName] = count; return propName; // Count me in }; } const counter = createCounter(); console.log(counter()); // Output: "count1" console.log(counter()); // Output: "count2"

Combining Dynamic Properties

And for the finale, let's mix-and-match dynamic keys:

const keys = ['alpha', 'beta', 'gamma']; const values = [1, 2, 3]; let resultObj = {}; keys.forEach((key, index) => { resultObj[key] = values[index]; // Mix and match }); console.log(resultObj); // Output: { alpha: 1, beta: 2, gamma: 3 }

Ready for Showtime: Compatibility & Transpilation

Taking into Account ES6 Support

Before deploying, remember to check your script's browser compatibility. You don't want to disappoint your audience:

const key = "enabledFeatures"; const knowsES6 = true; const myScript = { [key]: knowsES6 // Fingers crossed! }; // May ruin the party for older browsers

In case of compatibility issues, meet your backstage friend: Babel - an ES6 to ES5 transpiler.

Deploying with Webpack

As your code scales, consider using webpack. It’s like having a stage manager that takes care of your show from behind the scenes.