javascript - 对属性名称中包含数字的对象进行排序和过滤
问题描述
我试图过滤掉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);
解决方案
假设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;
}, []);
推荐阅读
- python-3.x - 熊猫中是否有任何软件包可以根据其他列计算列的选定部分值的平均值
- swift - Swift KVO 绑定未更新
- centos7 - 无法启动 OpenLDAP 服务器守护程序
- apache-spark - 如何使用 Spark Session 列出 S3 存储桶中的文件?
- javascript - 如何在 javascript 中设置 cookie?TT(Django 项目)
- php - 通过键排列查找值,php
- kubernetes - 如何使用 PodTemplate
- java - 如何从一个活动跳转到另一个活动并设置片段
- python - Python中主进程和子进程之间的动态通信
- r - 从单行中的同一 UserID 的不同列中收集非空行(POSIXct 格式)