Interpolate a JavaScript variable for an object key

I often find myself needing a dynamic value for a key in an object in JavaScript when both accessing and storing values on the object.

Let's start with how you'd do this without a dynamic key:

const args = {
    StaticKey: "some value"
}

If you know you want to use a dynamic key to store the value on, there are two ways to do that.

The first way: on object creation

For the purpose of demonstration, I'll create a constant called DyanmicKey. You can imagine that a function may take a string that it will use:

const someKey = "DynamicKey"

And on the object, rather than writing DynamicKey directly, I'll use the constant as the key:

const myDynamicObject = {
    [someKey]: "some value"
};

The important thing to note here is that the key is surrounded by square brackets ([ ]). Setting the key up this way tells JavaScript that what's inside needs to be interpolated as its value.

Here's what it would look like if you were to have the code above and console.log it:

const someKey = "DynamicKey"

const myDynamicObject = {
    [someKey]: "some value"
};

console.log(myDynamicObject); // {DynamicKey: "some value"}

The second way: setting the key/value pair on an existing object

Let's stick with the example above that we have myDynamicObject and it has DynamicKey on it still. How would I interpolate a variable for the key in the existing object?

Assuming we want to put another value on an existing object with a dynamic key, we can do:

const secondKey = "unicorns are"

myDynamicObject[secondKey] = "awesome sauce"

Now if I were to conole.log the myDynamicObject object, I would see:

{
    "unicorns are": "awesome sauce",
    DyanmicKey: "some value"
}

Now you have two tools to do dynamic variable interpolation for object keys.

Build something awesome!

Was this article useful? Share it on Twitter!