【问题标题】:Sort and Filter an Object that has numbers in its property names对属性名称中包含数字的对象进行排序和过滤
【发布时间】:2026-02-05 17:50:01
【问题描述】:

我正在尝试过滤掉将 mode 设置为 null 的项目,但是,在添加此 filter 后,所有项目都会消失,即使它们没有 @ 987654324@ 支持null

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
  .sort((a, b) => {
    return parseInt(a, 10) - parseInt(b, 10);
  })
  .filter(this.filterConfigsByBot)
  .filter(this.filterConfigsByStatus)
  .filter((item) => item.mode === null);

【问题讨论】:

  • 你能把函数filterConfigsByBotfilterConfigsByStatus的代码贴出来吗?这可能会帮助我们调试
  • 您声明I am trying to filter out items that has the "mode" props set to null,但您的代码却相反,只允许null 的模式。此外,还有 2 个其他过滤器功能您没有展示,所以我们不确定它们在做什么。看起来这要么需要作为一个简单的错字而关闭,要么需要添加更多信息。

标签: javascript arrays reactjs react-native sorting


【解决方案1】:

假设botConfig数据是以数字为属性的对象

const botConfigs = {
  2: { mode: null, botId: "10", status: "ACTIVE", },
  1: { mode: "A", botId: "20", status: "ACTIVE", },
  3: { mode: "C", botId: "15", status: "STOPPED", },
};

并且您想按(数字)属性排序,然后过滤值的属性。所以,这就是你的过滤器函数的样子:

filterConfigsByBot = (key) => {
  return botConfigs[key].botId !== "0"; // assuming botConfigs is available in scope
};

filterConfigsByStatus = (key) => {
  return botConfigs[key].status !== "STOPPED";
};

另外,请记住在末尾将map 键值botConfigs(如果需要):

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
    .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
    .filter(this.filterConfigsByBot)
    .filter(this.filterConfigsByStatus)
    .filter((key) => botConfigs[key].mode !== null) // to filter out items that has the `mode` set to `null`
    .map((key) => botConfigs[key]);

PS:您可以将三个过滤器组合成一个过滤器回调。

编辑:

使用reduce的简化版:

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
    .sort((a, b) => parseInt(a, 10) - parseInt(b, 10))
    .reduce((acc, curr) => {
    if (
        botConfigs[curr].botId !== "0" &&
        botConfigs[curr].status !== "STOPPED" &&
        botConfigs[curr].mode !== null
    ) {
        acc.push(botConfigs[curr]); // pushing values, not keys
    }
    return acc;
    }, []);

【讨论】:

  • > "假设 botConfig 数据是具有数字作为属性的对象" 对象键是字符串。
  • @ArunKumarMohan 如果您看到这些令人困惑的言论,请随时编辑我的答案。我会感谢你的努力。 + 它可能会给你badges
最近更新 更多