1

I have a child component that receives data via @Input() from parent component (array of objects). I map that data and push object in new array for each object from Input data array in ngOnChanges hook. My goal is to prevent duplicates objects being pushed in new array. Every time ngOnChanges fires new objects are being pushed to admins array. I've tried to use some method in if statement but it didn't help. Here is my OnChanges hook:

ngOnChanges() {
  this.adminsGroup.map(a => {
    this.authService.getSpecUser(a.user).subscribe(
      data => {
        data.position = a.permissions;
        this.admins.push(data);
      }
    )
  });
}

So I want to ensure that there is no data already in this.admins array before pushing it. Any help would be appreciated.

0

2 Answers 2

2

Checking against a specific property say 'id' in data for uniqueness.

if (!this.admins.some(el => el.id === data.id)) {
  this.admins.push(data);
}
Sign up to request clarification or add additional context in comments.

Comments

-1

If data has a unique ID you can just do:

let foundAdmin = this.admins.find(admin => admin.id == data.id);
if (foundAdmin == null)
    this.admins.push(data);

If it doesn't:

let foundAdmin = this.admins.find(admin => JSON.stringify(admin) === JSON.stringify(data));
if (foundAdmin == null)
    this.admins.push(data);

Comments

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.