Unable to understand object with array as key

I found some wild code on the Internet, I do not understand:

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

What does [action.subreddit] do? I thought object keys should be strings, but does this seem like an array?

I hope to mechanically understand how this code works.

Thank you!

+5
source share
1 answer

It is not an array as a key, it is an es6 way to use a variable (/ computed property) as a key. Consider this:

 var a = "foo"; function getKey() { return "myKey"; } var obj = { [a] : "bar", [getKey()] : "baz" }; console.log(obj.foo); // bar console.log(obj.myKey) // baz 

So, [action.subreddit] just sets the key name for any action.subreddit value.

+9
source

All Articles