Inspired by this article, I've been refactoring some old code.
However, I'm running into problems with passing arguments using Array.prototype.filter since the second parameter of Array.prototype.filter(callback, thisArg) binds the this-object in the callback but arrow functions don’t bind this.
In my example, I’m getting the keys from an associative array (yeah I know, technically not available in JavaScript) by using Object.keys(), then filtering that array by a property of their object in the associative array this[item].property, but that fails since this binding isn’t available.
So, embracing arrow functions, how does one pass parameters to the callback in filter()?
const arr = {
a: {
property: true,
otherProp: false
},
b: {
property: true,
otherProp: false
},
},
hasProperty = item => this[item].property,
getMatchingKeys = object => Object.keys(object).filter(hasProperty, object);
getMatchingKeys(arr);
You can use
Object.entries. It provides both the key and the value, so that you don't need the reference to the object itself:You could also use
bind-- not to bindthis, but a first argument:See also some other options in my answer to another question.