Learn how to interpolate a JavaScript variable for an object key for dynamic keys in a JavaScript object.
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.
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"}
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 console.log
the myDynamicObject
object, I would see:
{
"unicorns are": "awesome sauce",
DynamicKey: "some value"
}
Now you have two tools to do dynamic variable interpolation for object keys.
Build something awesome!
Subscribe to my Newsletter
Every other week I publish the Curiously Crafted newsletter.
In it, I explore the intersection of curiosity and craft: the people who make stuff, what they make and the way they pursue the craft of making.