Angular中如何通过JSON(B)的ID过滤JSON(A)中的车辆记录
在Angular中根据ID列表筛选车辆记录
我有两组JSON数据,一组是包含完整车辆信息的数组(JSON A),另一组是仅含ID的对象数组(JSON B),需要从JSON A中筛选出ID与JSON B匹配的记录。
原始数据
JSON (A) 车辆完整记录数组
[ { "id": 100, "brand": "Tes1", "vname": "Testname1" }, { "id": 200, "brand": "Tes2", "vname": "Testname2" }, { "id": 300, "brand": "Tes3", "vname": "Testname3" } ]
JSON (B) ID列表数组
[ { "id": 100 }, { "id": 300 } ]
实现步骤
- 提取目标ID集合:先把JSON B中的所有ID提取出来存入
Set,用Set的好处是查找效率远高于数组的includes方法。 - 筛选匹配记录:使用数组的
filter()方法遍历JSON A,保留ID在目标集合中的项。
Angular组件代码示例
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-vehicle-filter', templateUrl: './vehicle-filter.component.html', styleUrls: ['./vehicle-filter.component.css'] }) export class VehicleFilterComponent implements OnInit { // 原始车辆数据 vehicles = [ { id: 100, brand: 'Tes1', vname: 'Testname1' }, { id: 200, brand: 'Tes2', vname: 'Testname2' }, { id: 300, brand: 'Tes3', vname: 'Testname3' } ]; // 需要匹配的ID列表 idList = [ { id: 100 }, { id: 300 } ]; filteredVehicles: any[] = []; ngOnInit(): void { // 提取目标ID集合 const targetIds = new Set(this.idList.map(item => item.id)); // 筛选符合条件的车辆 this.filteredVehicles = this.vehicles.filter(vehicle => targetIds.has(vehicle.id)); } }
预期输出
[ { "id": 100, "brand": "Tes1", "vname": "Testname1" }, { "id": 300, "brand": "Tes3", "vname": "Testname3" } ]
内容的提问来源于stack exchange,提问作者Bhushan Khaladkar
相关产品推荐
相关产品推荐

