uiankosh
uiankosh

Reputation: 45

How to filter an array of object by comparing its id with the values of a different array

I have an array of object 'compareJson' using this I am displaying a list in html. I have an array 'Cars', using which I need to compare its value(1,4..) with 'id' attribute of 'compareJson' and needs to display the same list in HTML on click 'duplicate' button. If there is same id in multiple objects ,those all objects should display

app.component.html

<button (click)="duplicate()" >Get values </button>
<div *ngFor="let item of  compareJson">Item listed - {{item.details}}</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  compareJson = [
    {
      id: '1',
      details: 'Photography details'
    },
    {
      id: '1',
      details: 'Writing details'
    },
    {
      id: '3',
      details: 'Painting Details'
    }
  ];

  Cars = [1, 4];
}

Upvotes: 0

Views: 1492

Answers (1)

micaminoff
micaminoff

Reputation: 26

If I understand your question correctly, you want to get the objects from compareJson where the id attribute exists in the Cars array?

You could filter compareJson with values in the Cars array like this:

const matches = compareJson.filter((object) => Cars.includes(object.id));.

With your example matches would equal [{ id: '1', details: 'Photography details'}]

Upvotes: 1

Related Questions