Home > Software design >  Fill 2 different lists with .filter
Fill 2 different lists with .filter

Time:10-06

I am working with Angular 13 in a project where I have to populate a PickList component (it is a simple PrimeNG component, link is here).

The way we work with this component is simple. We receive from the backend a list of columns and the user has to select some or every single column in order to create a DataTable (also a PrimeNG component). Next, I am providing some code to show how we do it.

Column.ts

export interface Column {
  field: string;
  header: string;
  type: string;
  format: string;
  editable: boolean;
  widthColumn?: string;
}

column.service.ts

getColumns() {
    return this.http
      .get<any>(url)
      .toPromise()
      .then(res => <Column[]>res.data)
      .then(data => {
        return data;
      });
  }

picklist.component.ts

  sourceColumns!: Column[];
  targetColumns!: Column[];

ngOnInit(): void {
    this.columnService
      .getColumns()
      .then(columns => (this.sourceColumns = columns));
    this.targetColumns= [];
  }

But now, the backend has changed, and they added a new field, which is required, like this:

export interface Column {
      field: string;
      header: string;
      type: string;
      format: string;
      editable: boolean;
      widthColumn?: string;
      required: boolean;
    }

So now, by default, I have to fill those lists depending on if the column is required or not, with this criteria.

  • If the column is required, push to targetColumns
  • If the column is not required, push to sourceColumns

What I have tried so far:

this.columnService
      .getColumns()
      .then(columns => (this.allColumns = columns));

    let nonReqCol = this.allColumns.filter(column => column.required == false)
    let reqCol = this.allColumns.filter(column => column.required == true)

    this.sourceColumns= [...nonReqCol]
    this.targetColums= [...reqCol]

But it gives me this error on console:

ERROR TypeError: Cannot read properties of undefined (reading 'filter')

I can not figure it out why this is giving me this error, since I am doing (as far as I know) the same thing on both scenarios.

CodePudding user response:

Try this:

this.columnService
      .getColumns()
      .then(columns => {
           this.allColumns = columns;
           this.filterColumns();
       ));

// ...
private filterColumns(): void {
    const nonReqCol = (this.allColumns || []).filter(column => column.required == false)
    const reqCol = (this.allColumns || []).filter(column => column.required == true)

    this.sourceColumns= [...nonReqCol];
    this.targetColums= [...reqCol];
}

Basically you are filtering columns but they are not defined yet.

  • Related