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

如何从对象数组中筛选出ID唯一且totalTime为0的项?

筛选ID唯一且totalTime为0的对象数组

我需要从API返回的对象数组中筛选出满足两个条件的对象:

  • ID在数组中唯一(仅出现一次)
  • oeeCalculations.others.totalTime 的值为0

原始JSON数据

const response = [
  {  
      "id": "1",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "2",
      "oeeCalculations": {
          "others": {
              "totalTime": 744
          }
      }
  },
  {
      "id": "3",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "4",
      "oeeCalculations": {
          "others": {
              "totalTime": 0
          }
      }
  },
  {
      "id": "4",
      "oeeCalculations": {
          "others": {
              "totalTime": 744
          }
      }
  }
];

期望输出

const newResponse = [
    {  
        "id": "1",
        "oeeCalculations": {
            "others": {
                "totalTime": 0
            }
        }
    },
    {
        "id": "3",
        "oeeCalculations": {
            "others": {
                "totalTime": 0
            }
        }
    }
];

尝试过的代码(不符合需求)

这段代码只保留了ID唯一的项,但没有过滤totalTime的条件:

const values = Object.values(
      response.reduce((a, b) => {
        if (!a[b.id]) a[b.id] = b 
          return a
       }, {})
    )

解决方案

可以分两步实现:先统计每个ID的出现次数,再同时过滤两个条件:

// 统计每个ID的出现次数
const idOccurrence = response.reduce((acc, curr) => {
  acc[curr.id] = (acc[curr.id] || 0) + 1;
  return acc;
}, {});

// 筛选ID唯一且totalTime为0的对象
const newResponse = response.filter(item => {
  return idOccurrence[item.id] === 1 && item.oeeCalculations.others.totalTime === 0;
});

逻辑说明

  1. 用reduce遍历数组,生成一个记录每个ID出现次数的对象idOccurrence
  2. 用filter遍历原数组,只保留同时满足以下两个条件的对象:
    • 当前ID的出现次数为1(确保唯一)
    • totalTime的值为0

这样就能得到符合要求的结果数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:33:16