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
Laravel Eloquent ORM — a model class mapping to a database table with query methods
Laravel Eloquent ORM: The Complete Guide to Querying Your Database
June 16, 2026
Set vi as the default editor in Ubuntu — a terminal opening the vim editor
How to Set vi (Vim) as the Default Editor in Ubuntu
June 8, 2026
rsync says ALL DONE but files are missing — a terminal showing ALL DONE next to an empty folder
rsync Says “ALL DONE” but Files Are Missing: How to Verify
June 8, 2026
Migrate a website to a new server with rsync — files copying from an old server to a new one over SSH
How to Migrate a Website to a New Server With rsync
June 8, 2026
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026

You Might Also Like

WordPress search users by multiple fields — WP_User_Query search_columns + meta_query
Web Development

How to Search Users by Multiple Fields in WordPress

7 Min Read
Laravel updateOrCreate method shown in an Eloquent code snippet with insert and update branches
Web Development

Laravel updateOrCreate: Insert or Update Records in Eloquent

8 Min Read
Laravel migration column types cheat sheet
Web Development

Laravel Migration Column Types — Cheat Sheet

5 Min Read
Check if an element is hidden or visible with jQuery
Web Development

How to Check if an Element Is Hidden or Visible with jQuery

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?