首页 > 解决方案 > 对属性名称中包含数字的对象进行排序和过滤

问题描述

我试图过滤掉mode设置为的项目null,但是,添加后filter所有项目都会消失,即使它们没有mode属性 at 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);

标签: javascriptarraysreactjsreact-nativesorting

解决方案


假设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;
    }, []);

推荐阅读