Jack
Jack

Reputation: 1

Rxjs: How to filter data based on inner value of a list?

I retrieve data by using the following method:

this.employeeService
    .getList()
    .subscribe((list: any) => {
        this.list = list;
});

But there are 2 property in the list, one of them is data, the other is count. So, I need to apply filter according to list.data.isManager property without destructing list (I need to keep data and count properties). So, I need something like that:

this.employeeService
    .getList()
    .subscribe((list: any) => {
        this.list = list.filter(x => x.data.isManager === true);
});

But as the list is not array, it throws error. I need to apply filter according to list.data.isManager. So, how can I fix this problem? Should I use map operator?

Here is sample data of the list variable:

list:

count: 5
data: Array(5)
0: EmployeeListDto {isManager: true, id: 1, name: "John"}
1: EmployeeListDto {isManager: true, id: 2, name: "Mark"}
2: EmployeeListDto {isManager: true, id: 3, name: "Alice"}
3: EmployeeListDto {isManager: true, id: 4, name: "Mary"}
4: EmployeeListDto {isManager: true, id: 5, name: "Federic"}

Upvotes: 1

Views: 518

Answers (4)

Abhishek Kumar Pandey
Abhishek Kumar Pandey

Reputation: 457

If you want to process your data is reactive way, you can process your filtering like

this.employeeService
.getList()
.pipe(
  concatMap(arr => from(arr)),
  filter((ele: any) => ele.isManager)
 )
.subscribe((list: any) => {
    this.list = list;
});

Upvotes: 1

Gérôme Grignon
Gérôme Grignon

Reputation: 4228

isManager isn't a property of data but a property of an item of the data array.

So you need to place your filter on your data property (and keep the count property):

const filteredList = list.data.filter(item => item.isManager);
this.list = {
  count: filteredList.length,
  data: filteredList
}

Upvotes: 2

SeleM
SeleM

Reputation: 9638

Merely:

this.list ={ 
  data: list.data.filter(x => x.isManager),
  count: // ...
};

The value of count could be

  1. list.count if you want the original count
  2. list.data.filter(x => x.isManager).length if you want the after-filtering count. In this case, it is cleaner to do :
    this.list ={ 
          data: list.data.filter(x => x.isManager),
        };
    
     this.list['count'] = this.list.data.length;

** you do not need to x.isManager === true, javascript manage it internally.

Upvotes: 1

zahra zamani
zahra zamani

Reputation: 1375

data inside the list is a array so you can use filter

 this.list = list.data.filter(x => x.isManager === true);

Upvotes: 1

Related Questions