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

ES6如何过滤含随机UUID键的对象?

问题分析与解决方案

错误原因

你当前的代码逻辑是过滤对象的键(UUID字符串),但你的需求是筛选子对象中Type属性为Portfolio的条目——两者筛选的维度完全不匹配,所以自然得不到任何结果。

正确实现方案

方案一:基于Object.keys + filter + reduce

修改过滤逻辑,不再判断键,而是判断每个键对应子对象的Type属性:

const allowed = ['Portfolio'];
const filtered = Object.keys(portfoliosData)
  .filter(key => allowed.includes(portfoliosData[key].Type)) // 改为检查子对象的Type字段
  .reduce((obj, key) => {
    obj[key] = portfoliosData[key];
    return obj;
  }, {});

方案二:用Object.entries + Object.fromEntries(更简洁)

利用Object.entries直接获取键值对数组,过滤后再转回对象:

const allowed = ['Portfolio'];
const filtered = Object.fromEntries(
  Object.entries(portfoliosData).filter(([_, value]) => allowed.includes(value.Type))
);

效果说明

执行上述代码后,会保留原对象中所有Type为Portfolio的子对象,结果如下:

{
  "ed89d5a3-464b-4bd7-b9bb-e42ee87f6520": {
    "Id": "ed89d5a3-464b-4bd7-b9bb-e42ee87f6520",
    "ExternalSecurityListId": null,
    "CreatorId": "557fa8b2-59db-430d-9595-cd17884c9151",
    "Name": "Chris Portfolio Two",
    "PartnerName": null,
    "Type": "Portfolio",
    "CostBasis": 100000,
    "Processing": false,
    "NotificationSettings": {
      "SourceId": "ed89d5a3-464b-4bd7-b9bb-e42ee87f6520",
      "SourceType": "SecurityList",
      "ChannelTypes": null,
      "NotificationFilters": []
    },
    "Owner": null,
    "SharingStatus": "None",
    "CreatedDate": "2023-03-20T19:20:02.16Z",
    "ModifiedDate": "2023-03-20T19:20:17.117Z",
    "IsGroup": false,
    "UnderlyingSecurityListIds": [],
    "MaturingSoon": false
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:27:45