How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Use a Variable as an Object Key in JavaScript
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Use a Variable as an Object Key in JavaScript
Web Development

How to Use a Variable as an Object Key in JavaScript

how7o
By how7o
Last updated: May 23, 2026
5 Min Read
Use a JavaScript variable as an object key
SHARE

To use a variable as an object key in JavaScript, wrap the variable in square brackets inside the object literal: { [variable]: value }. This is ES6’s computed property names syntax — the expression in brackets is evaluated and the result becomes the key.

Contents
  • The problem
  • The fix — computed property names
  • Pre-ES6 alternative — build and assign
  • Computed keys with expressions
  • Multiple computed keys at once
  • Combine with spread / rest
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-05-17 on modern browsers and Node 20+. Originally published 2022-09-15, rewritten and updated 2026-05-17.

The problem

function setStorageValue(objectKey, objectValue) {
    // BUG: the literal string "objectKey" becomes the key,
    // not the value of the variable
    chrome.storage.local.set({ objectKey: JSON.stringify(objectValue || {}) });
}

In an object literal, a bare identifier is treated as a string. { objectKey: x } always produces { "objectKey": x }, regardless of what’s stored in the objectKey variable.

The fix — computed property names

function setStorageValue(objectKey, objectValue) {
    chrome.storage.local.set({
        [objectKey]: JSON.stringify(objectValue || {})
    });
}

The [objectKey] wrapper says “evaluate this and use the result as the key.” Calling setStorageValue('userDetails', { ... }) now produces { userDetails: '...' } as expected.

JS dynamic object keys — computed property names, bracket assignment, expressions in keys

Pre-ES6 alternative — build and assign

function setStorageValue(objectKey, objectValue) {
    const data = {};
    data[objectKey] = JSON.stringify(objectValue || {});
    chrome.storage.local.set(data);
}

Build an empty object, assign the property with bracket notation, then pass the object. Functionally identical to the computed-property form, just two lines longer.

Computed keys with expressions

const id     = 42;
const prefix = 'user';

const obj = {
    [`${prefix}_${id}`]: { name: 'Alice' },
    ['count_' + id]:     1,
    [getKey()]:          'computed at call time',
};

// obj is { user_42: {...}, count_42: 1, ...whatever getKey() returned }

Any expression that returns a string (or Symbol) can go in the brackets — template literals, concatenations, function calls. Useful for building objects whose shape depends on runtime state.

Multiple computed keys at once

function makeUser(id, name, role) {
    return {
        [`user_${id}_name`]: name,
        [`user_${id}_role`]: role,
    };
}

makeUser(42, 'Alice', 'admin');
// { user_42_name: 'Alice', user_42_role: 'admin' }

Combine with spread / rest

function updateField(obj, fieldName, newValue) {
    // Non-mutating: return a new object with one field changed
    return { ...obj, [fieldName]: newValue };
}

const user        = { name: 'Alice', role: 'user' };
const promoted    = updateField(user, 'role', 'admin');
// promoted: { name: 'Alice', role: 'admin' }
// user:     unchanged

Common React/state-management pattern: spread the existing object, then override one or more keys with computed names. The original object stays untouched (handy for immutable updates).

Frequently asked questions

Why does { key: value } use key as a literal string instead of the variable’s value?

JavaScript treats bare identifiers in object literals as string keys by convention — { key: 1 } is shorthand for { 'key': 1 }. To say “use the variable’s value as the key,” wrap the variable in square brackets: { [key]: 1 }. That’s the ES6 computed-property syntax.

Can I compute keys from expressions, not just variables?

Yes — the brackets can contain any expression: { ['user_' + id]: data }, { [`${prefix}-${id}`]: data }, { [getKey()]: data }. The expression is evaluated and its result (coerced to string or symbol) becomes the key.

How is this different from obj[key] = value?

obj[key] = value mutates an existing object — adds or overwrites a property. The computed-property syntax { [key]: value } is used inside an object literal to construct a new object with that key. Both produce the same shape; pick by whether you’re building or modifying.

Are object keys always strings?

Almost — keys are strings or Symbols. Numbers, booleans, and other primitives are coerced to strings when used as keys (obj[1] and obj['1'] reach the same property). Symbols are the exception: they remain Symbols and aren’t enumerable in for...in loops or Object.keys(). Use Symbols when you want “private” properties that won’t show up in standard iteration.

Related guides

  • How to Get N Elements from an Array in JavaScript
  • How to Get the First Character of a String in JavaScript
  • How to Check if a JavaScript String Is a Valid URL

References

MDN computed property names: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#computed_property_names.

TAGGED:JavaScriptobjects

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Select the last child element with jQuery How to Select the Last Child Element in jQuery
Next Article Enforce a minimum phone-number length in WooCommerce checkout How to Set a Minimum Length for Phone Numbers in WooCommerce
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Run Laravel queue workers with Supervisor
How to Run Laravel Queue Workers in Production with Supervisor
May 23, 2026
Nginx as a reverse proxy for a Node.js app on Ubuntu
How to Set Up Nginx as a Reverse Proxy for Node.js on Ubuntu
May 23, 2026
Install and configure Redis on Ubuntu for Laravel and WordPress
How to Install and Configure Redis on Ubuntu (for Laravel & WordPress)
May 23, 2026
Harden a fresh Ubuntu VPS with UFW, Fail2Ban, and SSH key auth
How to Harden a Fresh Ubuntu VPS: UFW + Fail2Ban + SSH Key Auth
May 23, 2026
Set up Let's Encrypt SSL with Certbot on Ubuntu
How to Set Up Let’s Encrypt SSL with Certbot on Ubuntu (Apache & Nginx)
May 23, 2026

You Might Also Like

Laravel unknown column CONCAT fix — DB::raw and selectRaw bypass identifier escaping
Web Development

How to Fix “Unknown column ‘CONCAT'” in Laravel

8 Min Read
Laravel MySQL variable in select — @name := assignment chains values across select items
Web Development

How to Set a MySQL Variable in Laravel Query Builder Select

8 Min Read
WooCommerce auto add to cart on visit — template_redirect hook and cart dedup
Web Development

How to Automatically Add a Product to Cart on Visit in WooCommerce

8 Min Read
Keep the first N characters of a JavaScript string with slice
Web Development

How to Keep Only the First N Characters of a String in JavaScript

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?