Using Javascript to sort through a JSON data set

Having trouble filtering a JSON using the filter method. The allProducts are returning correctly, but I can't seem to get the clubProducts to work as expected. Any assistance would be greatly appreciated. Thank you.

const state = {
  added: [],
  all: [
    {
      id: 'bcd755a6-9a19-94e1-0a5d-426c0303454f',
      name: 'Iced Coffee',
      description: 'Coffee, now featuring ice.',
      image: 'https://images.com',
      price: 899,
      fxCategory: 'Coffee'
    },
    {
      id: 'cc919e21-9a19-94e1-ace9-426c0303454f',
      name: 'The 2ndItem',
      description: 'Wouldn't you like to know.',
      image: 'https://images.com',
      price: 499,
      fxCategory: 'Club'
    }
  ]
}

const getters = {
    allProducts: state => state.all,
    clubProducts: state => function () {
        return state.all.filter(item => item.fxCategory == 'Club')
    }
}

UPDATE: Revised code with latest attempt based on suggestions given.

Answer №1

You've made a couple of errors: the filter() method can only be used on an array (such as state.all in this situation), and you forgot to enclose the string 'Club' in quotes for your comparison.

In addition, you can simplify your filter() function like so:

clubProducts: state.all.filter(item => item.fxCategory == 'Club')

Check out the documentation for more information.

Answer №2

As pointed out by @Reyedy, you can directly call the filter function in the 'clubProducts' field and the example works.

However, an error may occur if you use single quotes in the 'description' field.

Try using state.all instead.

description: "Wouldn't you like to know.",

instead of

description: 'Wouldn't you like to know.',

This is the only part where I encountered an error when trying to replicate your example.

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

Obtain the YouTube video ID using Jquery and the .match() function

Struggling to get my code working properly, almost there! My goal is to use jquery to extract only the video URL from a given input. This is the code I have so far: var url = 'http://www.youtube.com/watch?v=bxp8NWvIeSo'; $results = url.ma ...

Inquiring about the integration of CodeIgniter with Javascript and AJAX

Recently delving into Codeigniter and strategizing for a substantial application. Feeling a bit perplexed about CI's handling of JS files and AJAX requests. Opting for mod_rewrite with my project. In the typical webpage setup, I'd link indiv ...

Display JSON information in a table within a dropdown menu

I have a JSON dataset where each key is represented as a column in a table. I am looking to populate each column with data from the JSON as select boxes. For example, I want to display all "country" values from the JSON as select options in the COUNTRY col ...

Vue and Moment JS facing a challenge with today's date validation

I am developing a VueJS application that includes a form component. Within this form, there is a field for selecting dates. My goal is to display an error message if the chosen date is older than today's date. Essentially, the selected date should ...

SonarQube flagging a suggestion to "eliminate this unnecessary assignment to a local variable"

Why am I encountering an error with SonarQube? How can I resolve it since the rule page does not offer a specific solution? The suggestion is to eliminate the unnecessary assignment to the local variable "validateAddressRequest". validateAddress() { ...

What is the best way to combine JSON objects from a two-dimensional array into a single array using JavaScript?

I have a JSON object within an array that I want to push to an employeeArray. employeeArray =[ [ { "ID":"967", "NAME":"Dang, Lance D", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e426f6 ...

The concept of "HTML paragraph shifting"

I am looking to implement a feature similar to paragraph sliding, but I am struggling to explain it clearly. For demonstration purposes, I have added it to my website for you to view. Please note that it may take some time to load. The paragraphs slide s ...

Testing with jasmine-nodejs and utilizing the done() function to finish asynchronous tests

I am facing difficulties while setting up unit tests for my NodeJS application and running them with Jasmine. The issue arises when I use the done function in Jasmine tests. Whenever I include the done function, I encounter an error message stating: Warnin ...

Exploring the possibilities of integrating React with multiple Material UI dialogs

My goal is to have two dialog boxes, one for the sign-up page and another for the login page. When a user clicks on the sign-up button on the top page, the sign-up screen should appear. Likewise, when they click on the login button on the sign-up page, the ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

transmit JSON formatted form data to an AngularJS platform

I have a webpage built on AngularJS with a login feature. I want to iframe this webpage onto my own page and automatically log in my users. Upon inspecting the AngularJS site, I noticed that the login procedure expects a json object. I have tried multipl ...

Understanding Java and JavaScript variables within a JSP webpage

I am currently working on populating a pie chart from Google with data fetched from my database. Although I have successfully retrieved the desired results in my result set, I am facing challenges in converting my Java variables into JavaScript variables ...

Is the value being used as the key for the array of objects?

Here is an array of objects: { 'data': [{ value: 1000, year: 1990 }, { value: 1001, year: 1990 }, { value: 1002, year: 1990 }, ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

Steps for creating an edit feature when hovering over a div

Is there a way to implement a hover effect on a dynamically created table to display a small edit button in the top right corner of each cell? The goal is to have this button trigger a popup window when clicked. Something similar to the image below: https ...

Is there a way to record form choices upon submission?

How can I retrieve selected options from a form upon submission? I have a basic HTML form that triggers a JavaScript function on exit. However, I am unsure of how to capture the chosen option from the <select> element. Please refer to the code snip ...

Tips for extracting information from an HTML table into a function using Google Apps Script

I am experiencing difficulties in coding this. I have attempted to use google.script.run but it's not working as expected. When I click the button "Approved," the data should be sent to a function, but I'm unsure of what steps to take next. I fee ...

What should you choose between XDM and JSONP to bypass the same origin policy?

I am currently in the process of developing a JavaScript widget that retrieves approximately 4-6KB of data from a WCF service that I have hosted. This widget utilizes the canvas tag (HTML5) to create various charts. My goal is to make it easy for anyone to ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

When utilizing AJAX within a for loop, the array position may not return the correct values, even though the closure effectively binds the scope of the current value position

Is this question a duplicate of [AJAX call in for loop won't return values to correct array positions? I am following the solution by Plynx. The issue I'm facing is that the closure fails to iterate through all elements in the loop, although the ...