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

如何从包含对象数组的字典中筛选指定id的对象并生成count值数组

如何从包含对象数组的字典中筛选指定id的对象并生成count值数组

嗨,我来帮你搞定这个问题!你已经找对了第一步的方向——Object.values(objDict)确实能把字典里所有的对象数组提取出来,接下来咱们结合数组的几个高阶方法就能轻松实现需求,具体看下面的步骤和代码:

实现思路

  1. 提取所有数据集数组:用Object.values(objDict)把字典的值(也就是那些包含id和count的对象数组)转换成一个二维数组,结构类似[[{...}, {...}], [{...}, {...}]]。
  2. 匹配目标id的对象:对每个数据集数组,用find方法找到id和目标值匹配的对象。
  3. 提取count值:从匹配到的对象中取出count,收集成最终的结果数组。

完整代码示例

const objDict = {
  dataset1: [ { id: 1, count: 6 }, { id: 2, count: 7 }, { id: 3, count: 8 } ],
  dataset2: [ { id: 1, count: 5 }, { id: 2, count: 4 }, { id: 3, count: 3 } ]
};

const targetId = 2;
// 生成count数组
const countArray = Object.values(objDict).map(dataset => {
  // 在当前数据集中查找id匹配的对象
  const matchedItem = dataset.find(item => item.id === targetId);
  // 找到就返回count,没找到可以返回null/0,根据你的需求调整
  return matchedItem ? matchedItem.count : null;
});

console.log(countArray); // 输出: [7, 4]

边界情况处理(可选)

如果担心某些数据集里没有目标id的对象,导致结果出现null,可以额外加一步过滤,只保留有效的count值:

const countArrayFiltered = Object.values(objDict)
  // 先找到匹配的对象,找不到会返回undefined
  .map(dataset => dataset.find(item => item.id === targetId))
  // 过滤掉不存在的对象
  .filter(Boolean)
  // 提取count值
  .map(item => item.count);

console.log(countArrayFiltered); // 输出: [7, 4](和之前一样,但如果有数据集没匹配到,会自动过滤掉)

这种写法用了JavaScript的函数式编程风格,简洁且可读性高,完全能满足你的需求~

备注:内容来源于stack exchange,提问作者bairog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 10:23:08