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

如何排除指定键后获取status对象中值最小的键并做比较?

实现方案

步骤分解

要完成需求,咱们可以分成两步走:先从status里剔除prepped和draft这两个键,再从剩下的键值对里找出值最小的那个,最后拿active的值和这个最小值对比。

单个status对象的处理代码

先写一个处理单个status的函数,逻辑一目了然:

function checkActiveStatus(status) {
  // 1. 把status转成键值对数组,过滤掉不需要的键
  const filteredEntries = Object.entries(status).filter(([key]) => {
    return key !== 'prepped' && key !== 'draft';
  });

  // 极端情况处理:过滤后无有效键值对时返回false或按需调整
  if (filteredEntries.length === 0) return false;

  // 2. 找出值最小的那一项
  const minEntry = filteredEntries.reduce((prev, curr) => {
    return prev[1] < curr[1] ? prev : curr;
  });

  // 3. 对比active和最小值,返回结果
  return status.active <= minEntry[1];
}

遍历数组处理所有对象

如果要处理整个数组a,直接循环调用上面的函数就行:

const a = [
  {
    id: 2343,
    status: {
      prepped: 1,
      draft: 1,
      active: 2,
      maintenance: 6,
      on_rent: 8,
      unprepped: 10
    }
  },
  {
    id: 45,
    status: {
      prepped: 1,
      draft: 1,
      active: 2,
      unprepped: 10
    }
  }
];

// 处理数组里的每个对象,返回带结果的新数组
const results = a.map(item => ({
  id: item.id,
  isActiveValid: checkActiveStatus(item.status)
}));

console.log(results);
// 输出:[{id: 2343, isActiveValid: true}, {id: 45, isActiveValid: true}]

补充说明

  • 如果有多个键的值都是最小值(比如假设剩下的键里有两个值都是2),reduce会返回第一个遇到的那个,但这不影响对比逻辑——只要active的值小于等于这个最小值,就满足条件。
  • 加入了过滤后无有效键值对的判断,避免极端情况报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:20:13