【问题标题】:How to filter an array of object by comparing its id with the values of a different array如何通过将对象的 id 与不同数组的值进行比较来过滤对象数组
【发布时间】:2021-08-13 10:34:16
【问题描述】:

我有一个对象 'compareJson' 的数组,使用它我在 html 中显示一个列表。我有一个数组'Cars',我需要使用它来比较它的值(1,4..)和'compareJson'的'id'属性,并且需要在点击'复制'按钮时在HTML中显示相同的列表。如果多个对象中存在相同的 id,则应显示所有对象

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];
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    如果我正确理解您的问题,您想从compareJson 获取对象,其中id 属性存在于Cars 数组中?

    您可以使用 Cars 数组中的值过滤 compareJson,如下所示:

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

    在您的示例中,matches 将等于 [{ id: '1', details: 'Photography details'}]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多