Filter an array of objects in Angular using Typescript based on a specific value

I am working with an array that is fetching data from a JSON file. I have successfully stored an array of objects into my Task[]. Now, my goal is to retrieve the data based on their status ('Submitted' or 'Resolved' etc). Despite trying various methods, I have been unsuccessful in achieving this. Any assistance would be greatly appreciated.

data: [{
  taskname: 'Test1',
  taskId: '1',
  status: 'Submitted'
}, {
  taskname: 'Test2',
  taskId: '2',
  status: 'Resolved'
}, {
  taskname: 'Test3',
  taskId: '4',
  status: 'Submitted'
}, {
  taskname: 'Test4',
  taskId: '5',
  status: 'In Progress'
}, {
  taskname: 'Test5',
  taskId: '6',
  status: 'Resolved'
}, {
  taskname: 'Test6',
  taskId: '7',
  status: 'Submitted'
}
}]

Task.ts

export interface Task {
  taskId: any;
  taskname: any;
  status: any;
}

taskService.ts

getTask() {
  return this.http.get('../app/common/task.json')
    .toPromise()
    .then(res => < Task[] > res.json().data)
    .then(data => {
      return data;
    });

}

taskCompnent.ts

export class TaskComponent implements OnInit {
  taskList: Task[];
  datasource: Task[];
  sortedList: Task[];
  ngOnInit() {
    this.taskService.getTask().then(files => this.files = files);
    this.vecService.getData().then(taskList => {
      this.datasource = taskList;
      this.taskList = this.datasource; // Storing data into my task list array
    });
  }
}

This is how I attempted to filter by status:

 this.sortedList = this.taskList.filter(
      task => task.status ==='Submitted');

An error is being displayed below:

Cannot read property 'filter' of undefined

Answer №1

The reason for this issue is that promises and HTTP requests operate asynchronously. To address this, you must include the filter function within the callback of the promises. Placing it outside will result in taskList being undefined, making it impossible to apply the filter.

this.vecService.getData().then(taskList => {
        this.datasource = taskList;
        this.taskList = this.datasource; // Saving data to my task list array
        this.sortedList = this.taskList.filter(
        task => task.status === 'Submitted');

    });

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

Decoding JSON using GSON while dealing with dynamic child names

Having some trouble deserializing json using GSON. I attempted to use , but the variable field names in the "data" section are causing complications. My inquiry is: What should the structure of the main class be? How should the "data" class be stru ...

Organizing data with JavaScript: Transforming a flat array into nested JSON structures

In my front-end TypeScript file, there is a list called poMonths: 0: {id: 1, companyName: "company14", companyId: 14, flActive: true, purchaseMonth: "2019-12-15T00:00:00", purchaseMonthString: "Dec-2019" , year: 2019, month: "December"} 1: {id: 2, company ...

Where could my provider/service have gone missing?

After carefully following the guidelines in the official Angular 2 documentation, I created a CoreModule to handle my services. I also looked into some suggestions on: Providing core singleton services module in Angular 2 Resolving 'No Provider For ...

Determine if the "Privilege" array in JSON is set to "user" using

Here is the JSON data for my web server configuration: { "webserver_port": 80, "users": [ { "id": 1, "privilege": "Administrator", "username": "CorePack", "password": "$2b$10$xH5rvgSXbdnNsloKZeabFuC4wnhtxbIo4EeuzgdoiN/IOtrs ...

Error encountered with package.json on Azure due to Windows_NT 6.2.9200 operating system

I am encountering an issue while trying to deploy my angular2 website on Azure. The postinstall command in my package.json file is causing an error during the deployment process. I would appreciate any suggestions on what might be triggering this error. Pl ...

Splitting large components into smaller components

I am currently in the process of splitting the code from index.tsx into two separate files: firstTab.tsx and secondTab.tsx. As of now, I have only separated the code related to the first tab into firstTab.tsx, which can be viewed in the code editor. The co ...

The input value "HH:MM" does not match the expected format of 'FormatOptions' for this parameter

I created a function that takes in two parameters: data and format. I am attempting to define an ENUM(FormatOptions) for the "format" parameter. However, I encountered the following error: Argument of type '"HH:MM"' is not compatible with param ...

Initial values are not retained for nested form components upon submission

In an attempt to incorporate nested form components in Angular using reactive forms and ControlValueAccessors, I have been following a helpful guide available at the following link: While most of my implementation is working correctly, I am encountering o ...

Top way to extract JavaScript information from a basic 3-line CSV

I am grappling with a basic CSV file (imported via JQuery's $.ajax from the /data/league.csv on the same website) containing three lines in this specific structure: "Kimberlin Library","Queen's Building","Innovation Centre","etc etc" 8,2,0,-2 1, ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Subclass callback with parameters

Having some trouble with one of my TypeScript functions and I'm hoping it's not a silly question. I believe what I'm attempting should work in theory. Here's a simplified version of my issue to demonstrate where the problem lies (the o ...

Ensuring full enum coverage in TypeScript switch/case statements

I have 2 enums Color and Shape. The constant SHAPES_BY_COLOR connects shapes with different colors. In the future, I aim to execute specific actions depending on the selected color and shape using a switch/case statement. Is there a way for TypeScript to ...

To fetch a JSON stream, make a GET request using Unirest library

I am currently working on sending a GET request to the following URL: http://api.bitcoincharts.com/v1/trades.csv?symbol=krakenUSD&start=1303100000 Interestingly, when I use postman to send the request, everything goes smoothly. However, when I try t ...

Trouble with CDK Upgrade: unable to locate a similar command to "expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot())"

I just started using CDK and I'm currently in the process of upgrading the version for my code. However, in the test, the old CDK has the SynthUtils as shown below: expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot() I've looked in a ...

The problem of parameter being NULL in a post request in a .Net Core 3.0 Angular application

This is my first venture into the world of .Net Core Angular projects, so I apologize if my question appears to be too basic. Despite researching similar issues, I am still unable to resolve my problem, which leads me to believe that I must be making a mis ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

The "data path" should not include any extra elements or properties, such as allowed CommonJS dependencies

I'm currently running Angular v10 and facing an issue when trying to start my .net core / Angular application. Despite searching for a solution and updating everything to the latest versions, the problem persists. Although there are no errors report ...

Retrieving the selected checkbox value using Angular 2 TypeScript

I am currently working with Angular 2 Typescript and encountering an issue. I need to submit a form that includes checkboxes, but the problem lies in obtaining the values from the attributes of these checkboxes. Since the checkboxes are dynamic, there ca ...

Having trouble with Tailwind's 'select-none' class not functioning properly in mobile Safari

While working on my NextJS app, I encountered this code block: <div className="select-none"> bro </div> Surprisingly, even with the "select-none" class added, I can still select it in mobile Safari. I tried adding the ...

A guide to efficiently utilizing conditional dynamic import within a React application

Currently, I am working on a component that receives an array of strings as props. The goal is to iterate over each string in the array, capitalize it, and then dynamically import JSX elements from the "react-icons/si" module. While I have successfully acc ...