You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Angular中如何按血型与国家条件筛选获取唯一ID?

Angular中按条件筛选并提取唯一ID

原始JSON数据

先修正原始数据的语法错误(字符串需添加双引号):

[
  {
    "id": 1,
    "fname": "Tes1",
    "lname": "Testname1",
    "personaldata": {
      "bloodgroup": "A",
      "country": "IN",
      "email": "test@test.com"
    }
  },
  {
    "id": 12,
    "fname": "Tes2",
    "lname": "Testname2",
    "personaldata": {
      "bloodgroup": "B",
      "country": "US",
      "email": "test@test.com"
    }
  },
  {
    "id": 13,
    "fname": "Tes3",
    "lname": "Testname3",
    "personaldata": {
      "bloodgroup": "AB",
      "country": "IN",
      "email": "test@test.com"
    }
  }
]

需求与代码实现

你描述的需求(bloodgroup为"A"且country为"IN")和期望输出存在矛盾:按该条件筛选仅能得到id:1,但期望输出包含id:13(其bloodgroup为"AB")。以下提供两种对应实现:

1. 匹配期望输出的代码(筛选country为"IN"的记录)

// 假设数据存储在该变量中
const userData = [/* 上述修正后的JSON数据 */];

const filteredIds = userData
  .filter(user => user.personaldata.country === "IN")
  .map(user => ({ id: user.id }));

console.log(filteredIds);

2. 严格匹配原需求的代码(筛选bloodgroup为"A"且country为"IN"的记录)

const filteredIds = userData
  .filter(user => user.personaldata.bloodgroup === "A" && user.personaldata.country === "IN")
  .map(user => ({ id: user.id }));

console.log(filteredIds);

输出结果

  • 对应第一种代码的输出(匹配期望):
[{"id":1}, {"id":13}]
  • 对应第二种代码的输出(匹配原需求):
[{"id":1}]

内容的提问来源于stack exchange,提问作者Bhushan Khaladkar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:23:21