Issue in accessing JavaScript filter function within an object of functions: Unable to read properties of undefined (Vuex store)

Issue with Vuex Store Index.js:

I am encountering a problem while trying to filter an array using another array. When attempting to access the filter function within its object, I receive the following error:

TypeError: Cannot read properties of undefined (reading 'includes')
    at aspect_ratio (index.js?9101:72:1)

All my filter functions are stored in an object structured 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"]),
};

Within my getters section, I aim to utilize the aspect_ratio filter in this manner:

export const getters = {
  filtered_items(state) {
      const filteredArray = [...state.allHandhelds].filter(
        filter_functions[state.current_sort]
      );
      return filteredArray.filter(filter_functions.aspect_ratio);
    } 
  },
};

This is how my state is defined:

export const state = () => ({
  current_sort: "all_handhelds",
  current_features: ["a", "b", "c"],
  allHandhelds: [],
});

Initial Thoughts:

It appears that there may be an issue when accessing the object containing the filter functions or specifically retrieving the current_features array from the state.

Interestingly, moving the filter function outside the object and directly incorporating it seems to solve the problem. For example:

return filteredArray.filter((obj) => state.current_features.includes(obj["Aspect Ratio"]));

Any insights on what could be causing this error?

Answer №1

Hello Lisa, I encountered the same issue and managed to resolve it by utilizing arrow functions. When using the filter function, accessing class variables "this" can be tricky. However, arrow functions provide a way to overcome this limitation.

For instance, if you need to retrieve the name of an object within an array of objects:

This is the original code that causes the error:

this.array.filter(function (el) { return el.id == this.variableClass.id })[0].name

By using arrow functions, the issue was resolved:

this.array.filter((el) => { return el.id == this.variableClass.id })[0].name

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that certain data (such as images) may not be accessible for web scraping?

As I attempt to extract the image URL from a website using Python, Selenium, and Firefox, it appears that I have encountered a situation where it is proving difficult. Despite there being no <​img> element present, the image is still visible on the ...

Transmit information from the frontend to the backend using JavaScript and the Express framework

After creating a custom variable in my frontend to store data, I needed to access the same data in my Express backend. The JavaScript variable and the POST request code snippet are as follows: const dataPush = { urlSave: urlSave, ...

Customize Bootstrap layout on the fly

I have encountered a slight dilemma. I am attempting to implement something similar to the following: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com ...

What is the best way to implement a third-party library that utilizes an outdated import method in Angular 4.x?

Can anyone guide me on how to include the mathjs library in Angular 4.0 and use it within a component? Here are the steps I've taken so far: yarn add mathjs I believe there should be a method for injecting JS libraries during one of the build lifec ...

Sophisticated layering of partials and templates

I am facing a challenge in handling intricate nesting of templates (also known as partials) within an AngularJS application. To illustrate my predicament, I have created an image: As depicted, this application has the potential to become quite complex wi ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

VS Code sees JavaScript files as if they were Typescript

I have recently delved into the world of Typescript and have been using it for a few days now. Everything seems to be working smoothly - Emmet, linting, etc. However, I've encountered an issue when trying to open my older JavaScript projects in VS Cod ...

Is it necessary for me to be familiar with AngularJS in order to redesign an app for Angular 2+

I'm curious - when rewriting an application from AngularJS to Angular 2+, do you need to be familiar with both, or is knowing just Angular 2+ sufficient? ...

Using Sails.js server to power an Angular.js web application

Currently, I am in the process of creating a web application with Sailsjs for the backend and Angular.js for the frontend. To set up the Angular app, I utilized yeoman with the angular generator, while for the backend, I relied on the default Sails app gen ...

The jQuery change event is not triggered for <input type="file"> when a file is dropped on the label

I am currently developing a drag and drop file uploader that can be activated by either clicking the label or dragging a file onto the label. The input field includes a jQuery on change event that is triggered when a file is selected. However, it only see ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

Utilizing JQuery to load and manipulate SVG external DOM elements

Currently, I am in the process of creating an SVG document using Pydot. Below is a snippet of the document: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1 ...

Using browserify "require" in console: A step-by-step guide

My Rails project now includes the browserify and pinyin packages, thanks to the browserify-rails installation. To find out more about the pinyin package, check out this link: https://github.com/hotoo/pinyin var pinyin = require("pinyin"); console.log(pin ...

Issue with submitting input fields that were dynamically added using jquery

I created a table where clicking on a td converts it into an input field with both name and value. The input fields are successfully generated, but they do not get submitted along with the form. In my HTML/PHP : <tr> <f ...

Arrange the names in ascending order within arrays in an array

If we consider a scenario where an array of names is provided, let names = [ [ ['firstName', 'Rachel'], ['age', 10], ['gender', 'female'], ], [ ['firstName', 'Sam'] ...

Utilizing jQuery/AJAX to interact with database in Django

Seeking assistance as I've tried multiple times with little success. Using the tango with Django book and various online examples, but no luck. Currently designing a 'Fake News' website with Django featuring a mini-game where users vote on w ...

Utilizing ajax for retrieving content from a local text file

I have a duo of files called index.html and mytext.txt residing in the same directory. I am aiming to retrieve the contents of mytext.txt through an ajax call within index.html. The provided code works successfully in Firefox, but unfortunately fails in Ch ...

Check if the user is null using React's useEffect hook and then perform a

I am currently working on implementing a protected route in Next JS. I have included a useEffect to redirect to the sign-in page if there is no user detected. const analytics = () => { const { userLoaded, user, signOut, session, userDetails, subscri ...

Leverage the power of Angular's $http module in conjunction with Django's urlpatterns to fetch

I am attempting to send a $http GET request to a Django URL pattern in order to retrieve a .json file. Is it possible to use urlpatterns to return a file instead of a view? Is this scenario achievable, or are there limitations preventing this from working ...

Retrieve JSON object from dropdown menu

I need to retrieve the object name from a dropdown menu when an item is selected. How can I access the object from the event itemSelect? Thank you for your attention. View Dropdown Menu XML code: <core:FragmentDefinition xmlns="sap.m" xmlns:c ...