[JS] Dynamically Set Properties in Object
What can be expected from this post?
Let me share a small story from my recent coding adventure.
I was building a simple two-player game in JavaScript. You know, the classic kind — one player is X, the other is O. Everything was going smoothly… until I wanted to let players customize their names.
Instead of hardcoding names like "Player 1" and "Player 2", I wanted something dynamic:
When a user typed in a new name, I wanted to update my players object to reflect it.
That’s when I ran into a common JavaScript gotcha — how do you dynamically set a property on an object when you don’t know the key in advance?
In this post, I’ll walk you through the solution I found, and why [bracket notation] in JavaScript is so powerful when you're working with dynamic data — especially in React.
Solution: Use [] for Dynamic Keys in React State
In my case, I was using React and had a state object to store player names, like this:
const [players, setPlayers] = useState({
X: "Amy",
O: "John",
});
Later, I wanted to update just one of the players’ names based on user input.
Here’s what didn’t work:
setPlayers((prevPlayers) => ({
...prevPlayers,
symbol: newName, // This sets a key literally named "symbol"
}));
What is correct:
To dynamically update the right key (X or O), I used bracket notation:
function handleNameChange(symbol, newName) {
setPlayers((prevPlayers) => ({
...prevPlayers,
[symbol]: newName, // Use [] to evaluate the variable
}));
}
Why this works?
By wrapping the key in square brackets — [symbol] — we’re telling JavaScript:
"Use the value of this variable as the key name."
So if symbol = "O" and newName = "Charlie", the result would be:
{
X: "Amy",
O: "Charlie", // Successfully updated!
}
Without the brackets, it would have looked like this instead:
{
X: "Amy",
O: "John",
symbol: "Charlie", // Wrong key added
}
Conclusion
That little feature in my game taught me a big lesson:
When dealing with object keys that come from user input, state, or any kind of dynamic data — bracket notation is your best friend.
It's small details like this that make a huge difference in building robust and bug-free components. Whether you're updating game players, form fields, or any dynamic structure, just remember:
- Dot notation (
obj.key) is for static keys. - Bracket notation (
obj[key]) is for dynamic keys.
Comments ()