3

How to compare 2 array of objects and when value is matched then checked angular material checkbox? eg: In this case operator object is matched so checkbox is checked for operator

app.ts

const arr1 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"2",
      "name":"admins"
   },
   { 
      "id":"3",
      "name":"client"
   },
   { 
      "id":"4",
      "name":"developer"
   }
]
const arr2 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"3",
      "name":"client"
   }
]

this.arr1.forEach(a1Obj => {
    this.arr2.some(a2Obj => {
        if (a2Obj.id === a1Obj.id) {
            console.log(a1Obj);
        }
    })
});

app.html

<div class="col" *ngFor="let group of groups; let i = index">
    <mat-checkbox value="group.id" [labelPosition]="'after'" [checked]="true" (change)="assignGroups($event, group.id)">
        {{ group.name }}
    </mat-checkbox>
</div>

2 Answers 2

1

You can add an array in which you will push the common values and then check everytime if current group exists in commonArray using isCommonElt function:

TS file

commonArray = [];
this.arr1.forEach(a1Obj => {
  this.arr2.some(a2Obj => {
    if (a2Obj.id === a1Obj.id) {
      console.log(a1Obj);
      this.commonArray.push(a1Obj);
    }
  })
});

isCommonElt(id: any): boolean {
  return this.commonArray.some(elt => elt.id === id);
}

HTML file

<div class="col" *ngFor="let group of groups; let i = index">
    <mat-checkbox value="group.id" [labelPosition]="'after'" [checked]="isCommonElt(group.id)">
        {{ group.name }}
    </mat-checkbox>
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

Try like below,

.ts file

const arr1 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"2",
      "name":"admins"
   }
];
const arr2 = [ 
   { 
      "id":"1",
      "name":"operator"
   },
   { 
      "id":"3",
      "name":"client"
   }
];

isEnableCheckbox: boolean = false;

constructor() {
  this.isEnableCheckbox = this.checkIsObjectIsEqual();
}

checkIsObjectIsEqual() {
    // The below resultArray will give the common objects from the both comparing arrays
    let resultArray = this.array1.filter(a1Obj => {
        return this.array2.some(a2Obj => {
            return a2Obj.id === a1Obj.id;
        });
    });

    if (resultArray.length > 0) {
        return true;
    } else {
        return false;
    }
}

.html file

<mat-checkbox [checked]="isEnableCheckbox">some label</mat-checkbox>

2 Comments

it's checked all checkboxes
how the groups array looks?. Could you please paste that code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.