Home > Enterprise >  How to filter multiple array in object then display
How to filter multiple array in object then display

Time:01-12

const data = {
      test1: [
        {error: ''},
        {error: ''},
      ],
      test2: [
        {error: ''},
        {error: 'theres an error in this field'},
        {error: 'theres an error here'},
      ],
      test3: [
        {error: ''},
        {error: 'theres an error'},
        {error: 'theres an error here'},
      ]
    };

how to filter data with an error value and display on it?

  const test1 = data.test1.filter(x => x.error !== ''); 
        const test2 = data.test2.filter(x => x.error !== ''); 
        const test3 = data.test3.filter(x => x.error !== ''); 
        
            <div>
               <div *ngFor="let test of test1">
                    {{test.error}}
               </div>
               <div *ngFor="let test of test2">
                    {{test.error}}
               </div>
               <div *ngFor="let test of test3">
                    {{test.error}}
               </div>
            </div>

I'm not sure it this is the correct way.

What I'm trying to do is display all the errors by listed without a space just like this

theres an error in this field
theres an error here
theres an error
theres an error here

CodePudding user response:

Since you are using Angular, and therefore Typescript, you should type your variables. .some() returns a boolean, not an array, so const test1 should be const test1:boolean. And now you see you can't do *ngFor="let test of test1" on a boolean.

Replace .some with .filter, which does return an Array, and you should be good.

const test1: {error:string}[] = data.test1.filter(x => x.error !== '');

CodePudding user response:

You can extract all errors from data using:

interface ErrorResponse {
  error?: string;
}
const errors: ErrorResponse[] = Object.values(data).flat().filter(row => row.error);

and then display them using:

<div *ngFor="let response of errors">
   {{response.error}}
</div>

Refs: .filter(), .flat().

  •  Tags:  
  • Related