Billy Blob Snortin Billy Blob Snortin - 2 months ago 6
Javascript Question

Cannot understand object with array as key

I've found some wild code on the web i don't understand:

return Object.assign({}, state, {
[action.subreddit]: posts(state[action.subreddit], action)

What is
doing? I thought that object keys had to be strings but this appears to be an array?

I'm hoping to understand mechanically how this code works.

thank you!

mmm mmm

That's not an array as key, it's the es6 way to use a variable as the key. Consider this:

var a = "foo";
var obj = {
    [a] : "bar"

console.log(; // bar

So [action.subreddit] just sets the key's name to whatever value action.subreddit is holding.