5

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 [action.subreddit] 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!

Billy Blob Snortin
  • 1,101
  • 3
  • 11
  • 17

1 Answers1

9

That's not an array as key, it's the es6 way to use a variable (/ a computed property) as the 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's name to whatever value action.subreddit is holding.

baao
  • 71,625
  • 17
  • 143
  • 203