Struggling with filtering an array fetched from an API using VueJS

Currently, I am working on a Nativescript-Vue app and facing some challenges that I need help with.

The Scenario

I have data coming in from an API. Here is the structure of the data I receive:

{
"count": 9,
"results": [
    {
        "id": 1,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",            
        "gender": "male",
        "age": 32,
        "status": "active",

    },
    {
        "id": 3,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",            
        "gender": "male",
        "age": 32,
        "status": "active",

    },
    {
        "id": 4,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 34,
        "status": "inactive",

    },
    {
        "id": 6,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 65,
       "status": "inactive",
    },
    {
        "id": 2,
        "createdOn": "2020-04-08T12:10:46.924551+05:45",
        "modifiedOn": "2020-04-08T12:10:47.236475+05:45",
        "age": 19,
        "status": "pending",

    },

]

This code snippet below shows the Vue component I have implemented.

 export default {
data() {

    return{
        allData:[],
        total:[],
        active:[],
        inactive:[],
        pending:[]       

       }
},
mounted() {
   axios({ method: "GET", "url": "https://api.url" }).then(
       response =>
       {            

             this.allData = response.data.results,
             this.total = response.data.count               

         }, error => {
            console.error(error);
        }
   )       
},

computed:{
        active(){
            return this.allData.filter((status)=>{
                return this.allData.status.match("active");
                 })
            }

        },

  }

I aim to display the total number of records for active, inactive, and pending statuses in the app. For now, I'm focusing on the count for 'active' using this piece of code.

<Label class="numbers" :text="active.count" width="200" height="50" />

If anyone can point out where I might be making mistakes, I would greatly appreciate it.

Thank you in advance. Ashish A.

Answer №1

To begin, make sure to update your computed property in the following manner:

computed: {
    active() {
      return this.allData.filter(d => d.status === 'active')
    }
  },
}

It is important to note that using this.allData.status is not correct since status is a property of the objects within the allData array. While this.allData[0].status may have worked, it is unnecessary within the filter() method as each object can be accessed using the d variable.

Next, update your template as follows:

<Label class="numbers" :text="active.length" width="200" height="50" />

Keep in mind that active here is an array and arrays do not have a count property. Instead, you should use length to obtain the count of the active data.

Answer №2

Your current filter is not functioning as you had originally intended.

To correct this issue, adjust the code snippet below so that it filters correctly - resulting in an array of items that are currently active. If you only need the count of active items, simply add a .length at the end of the filter to return the number of active items instead.

computed: {
  current() {
    return this.allData.filter((item) => item.status === "active");
  }
}

If you require further details on the filter method, please refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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

What is the process for displaying images fetched from the API?

Currently, my front-end is built using React/Redux and the API side with AdonisJS. All of my images are stored within the API, and I need to find a way to display them on the front-end. Can anyone provide guidance on accomplishing this task? ...

Is there a way for me to incorporate the input parameter value passed to a JavaScript function into the popup that is being opened by the function itself?

I am not very proficient in PHP and JavaScript, and I'm facing an issue while trying to pass a value from a main page to a popup page that is defined within this main page. To provide more context: In my account.php page, there is a link like this: ...

Unable to Retrieve JSON Output

PHP Code: $contents = ''; $dataarray = file('/location/'.$_GET['playlist'].''); //Loading file data into array $finallist = ''; //Extract Track Info foreach ($dataarray as $line_num => $line) //Loopin ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

using regular expressions to find unclosed font tags that match on a single line

Even though regex is not typically recommended for parsing HTML, in this case we are dealing with a single line string input to a function. For example: <font color = "#ff0000"> hello </font>. I want the regex pattern to match only if the tag ...

Error encountered while invoking web server method in C# through ajax resulting in a 500 Internal Server Error

Occasionally encountering a 500 internal server error when calling a server method from an AJAX request has left me perplexed. The inconsistency of the issue, sometimes working fine and sometimes not, is baffling. To add to the confusion, no changes were m ...

How to extract column name from query result set using JavaScript in Snowflake database?

When querying in Snowflake with JavaScript inside a stored procedure, we typically receive a Result_set. How can the column names of the output result be retrieved using the JavaScript API? Please note that this inquiry is not about retrieving the values ...

Is there a tool that can help pinpoint the original collection for shared elements across multiple collections?

When given multiple collections/arrays, I am interested in identifying the common elements and which collections they belong to. This request is somewhat similar to this query, but there may be matching elements between collection1 and collection3, or eve ...

Using destructuring assignment in a while loop is not functional

[a,b] = [b, a+b] is ineffective here as a and b are always set to 0 and 1. However, using a temporary variable to swap the values does work. function fibonacciSequence() { let [a, b, arr] = [0, 1, []] while (a <= 255) { arr.concat(a) [a, ...

The changes made to the state array in react.js are not reflected in the DOM

In my React game implementation, I have the board set up as a two-dimensional array in the initial state of the parent component. The tiles on the board are rendered by looping through this array. Each tile receives a function as a prop that allows it to m ...

Issue with Codeigniter's AJAX functionality causing div reloading to not function as intended

I am currently facing an issue where I can display text directly from the database on a webpage. However, when I edit the text in the database, I want it to automatically reload and show the updated text without having to refresh the entire page. Unfortun ...

Is there a way to modify the color of the horizontal line within react-native-otp-inputs in the React Native platform?

Is there a way to customize the color of the horizontal line in react-native-otp-inputs for react native? I used react-native-otp-inputs to capture user OTP input, but now I want to change the color of the default black horizontal line to white. You can re ...

Internet Explorer versions 9 and 10 do not support the CSS property "pointer-events: none"

In Firefox, the CSS property pointer-events: none; functions properly. However, it does not work in Internet Explorer 9-10. Are there any alternative approaches to replicate the functionality of this property in IE? Any suggestions? ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Obtaining serverTime from a webpageWould you like to learn

Is it possible to retrieve the serverTime using jquery ajax functions like $.get() or $.post()? I am looking to store this serverTime in a variable that can be utilized later on in javascript. You can access the webpage at: To use the get and post functi ...

Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to ...

Discover the steps to inserting an icon into a tab using AngularJS

Hello, I am a beginner in angular js. Can someone please guide me on how to include an icon in a tab using angular js? Here is my current code: <tabset panel-tabs="true" panel-class="{{demoTabbedPanelClass}}" heading="{{demoTabbedPanelHeading}}"> ...

Troubleshooting ECONNREFUSED in NextJS API: App successfully runs in both deploy and development mode, but encounters issues when next build is executed

Detailing the Glitch I've developed an application using NextJS that incorporates an internal API, utilizing the getStaticProps methods to interact with the API. You can access the live app at this link: Additionally, you can find the project' ...