Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot understand object with array as key [duplicate]

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!

like image 326
Billy Blob Snortin Avatar asked Aug 18 '16 18:08

Billy Blob Snortin


People also ask

How do you check if an object has duplicate array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you avoid duplication in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

Can array have duplicate keys?

Code Inspection: Duplicate array keysReports duplicate keys in array declarations. If multiple elements in the array declaration use the same key, only the last one will be used, and all others will be overwritten.

Can an object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


1 Answers

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.

like image 73
baao Avatar answered Sep 28 '22 08:09

baao