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!
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.
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.
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.
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With