As front-end developers, we often work with objects in JavaScript. But did you know you can create object properties with names that are determined at runtime? This powerful feature in Javascript is called dynamic property names, and it can make your code more flexible and expressive.
What are dynamic property names in JavaScript?
Dynamic property names in JavaScript allow you to use variables or expressions as object keys. Instead of hardcoding property names, you can compute them on the fly. This is especially useful when working with data from APIs or when creating flexible data structures.
How it works
- Use square brackets
[]
to define a dynamic property name. More about the property accessors here. - You can use variables, expressions, or function calls inside the brackets.
- This feature is particularly useful for creating objects based on runtime values or transforming data.
1. Creating objects with runtime values:
Runtime values refer to values that are determined or computed while the program is running, as opposed to values that are known when you’re writing the code. In the context of dynamic property names, this means that the property names of an object can be determined based on the program’s state or user input at the time the code is executed.
const dynamicKey = 'age';
const person = {
name: 'Alice',
[dynamicKey]: 30 // Dynamic property name
};
console.log(person); // Output: { name: 'Alice', age: 30 }
In this example, [dynamicKey]
becomes 'age'
in the resulting object.
2. Transforming API responses:
const apiResponse = {
user_name: 'Alice',
user_email: 'alice@example.com'
};
const formattedUser = Object.keys(apiResponse).reduce((acc, key) => {
const newKey = key.replace('user_', '');
return { ...acc, [newKey]: apiResponse[key] };
}, {});
console.log(formattedUser);
// Output: { name: 'Alice', email: 'alice@example.com' }
By using [newKey]
to create properties on the fly, we can flexibly remove the ‘user_‘ prefix from any number of fields in the API response, creating a more concise object structure. This approach is particularly practical because it’s not limited to a predefined set of properties – it can handle changes in the API response without requiring code modifications. And, can be reused for different API responses.
Quick syntax tip
You can use any expression inside the square brackets, including template literals for more complex key generation:
const prefix = 'user';
const id = 42;
const user = {
[`${prefix}_${id}`]: 'John Doe'
};
console.log(user); // Output: { user_42: 'John Doe' }
With the JavaScript dynamic property names at your disposal, you’ll have another powerful tool in your JavaScript toolkit, allowing you to write more flexible and efficient code.
Related article: https://front-end.tips/how-to-add-conditional-object-properties-javascript/