'Access JavaScript filter function in object of functions: Cannot read properties of undefined (Vuex store)
The problem in my vuex store index.js:
I want to filter an array with another array. If I access the filter function in its object I get an:
TypeError: Cannot read properties of undefined (reading 'includes')
at aspect_ratio (index.js?9101:72:1)
I have all my filter functions in an object like this:
export const filter_functions = {
form_factor_landscape: (obj) => {
return obj["Form Factor"] === "Landscape";
},
form_factor_portrait: (obj) => {
return obj["Form Factor"] === "Portrait";
},
aspect_ratio: (obj) => state.current_features.includes(obj["Aspect Ratio"]),
};
In my getters I want to access the aspect_ratio filter like this:
export const getters = {
filtered_items(state) {
const filteredArray = [...state.allHandhelds].filter(
filter_functions[state.current_sort]
);
return filteredArray.filter(filter_functions.aspect_ratio);
}
},
};
my state is like this:
export const state = () => ({
current_sort: "all_handhelds",
current_features: ["a", "b", "c"],
allHandhelds: [],
});
My thoughts:
It seems like there is some problem with accessing the object with the filter functions. Or more precisely accessing the current_features array from the state.
Strangely if I just take the filter function outside the object and directly embedd it everything works. Like this:
return filteredArray.filter((obj) => state.current_features.includes(obj["Aspect Ratio"]));
Any idea what I'm doing wrong?
Solution 1:[1]
Hi Lisa I got this problem also and I solved it by using arrow functions. inside the filter function you cannot access to class variables "this". But you can use arrow functions to access it
as an example you want to get the name of an object inside an array of objects
this reproduces the error
this.array.filter(function (el) { return el.id == this.variableClass.id })[0].name
this fixed it
this.array.filter((el) => { return el.id == this.variableClass.id })[0].name
Solution 2:[2]
Just found a way how to access attribute.
var pages = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == "Solution.Pages" && t.GetCustomAttributes<IPRestrictAttribute>().Any());
var page = pages.FirstOrDefault(t => t.GetCustomAttributes<RouteAttribute>().Any(x => x.Template.Equals(context.Request.Path, StringComparison.OrdinalIgnoreCase)));
var attribute = page?.GetCustomAttributes<IPRestrictAttribute>();
I'm not saying it's optimal code but it's working. Pages variable should be outside middleware as static global...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user19157233 |
| Solution 2 | PetrK |
