javascript - JavaScript - 通过对象“过滤” - 最佳实践?
问题描述
通过对象“过滤”的最佳方法是什么?我有一个示例对象,如下所示:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 2925
},
"sourcemoney": {
"amount": 2925
},
"direction": "IN"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
{
"money": {
"amount": 1467
},
"sourcemoney": {
"amount": 1467
},
"direction": "IN"
},
]
}
通过它“过滤”以删除任何具有键值对的对象的最佳方法是什么"direction": "IN"
?
例如,我想删除方向设置为 IN 的两个对象,因此新对象变为:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
]
}
在一个数组中,我知道你可以使用该filter
功能吗?想知道尝试实现上述目标的最佳实践是什么?
解决方案
最佳实践是使用旨在进行过滤的方法:
response['example-feed'] = response['example-feed'].filter(f => f.direction != 'IN');
filter方法适用于数组,因此您需要过滤数组,而不是对象。
一个例子:
const response = {
"example-feed": [
{
"money": {
"amount": 2588
},
"sourcemoney": {
"amount": 2588
},
"direction": "OUT"
},
{
"money": {
"amount": 2925
},
"sourcemoney": {
"amount": 2925
},
"direction": "IN"
},
{
"money": {
"amount": 1921
},
"sourcemoney": {
"amount": 1921
},
"direction": "OUT"
},
{
"money": {
"amount": 1467
},
"sourcemoney": {
"amount": 1467
},
"direction": "IN"
},
]
};
response['example-feed'] = response['example-feed'].filter(f => f.direction !=
'IN');
console.log(response)
推荐阅读
- sql - 如何将变量连接到postgresql中的其他变量?
- c++ - 是否需要互斥锁才能将参数传递给 pthread?
- python - 以模式排序列表
- sql - 蜂巢查询以查找客户从当前交易日期起过去 10 天内的交易总数
- javascript - Vue路由器缺少参数
- python - 根据均值、标准差和偏度创建新的 pdf
- java - 即使请求正文中存在错误,BindingResult 也不会显示错误
- regex - 正则表达式:2 个表达式之间的 0 到 N 行
- android - Android Kotlin - 禁用 EditText 但不隐藏键盘
- c++ - 如何将不属于 QObject 的枚举暴露给 QJSEngine?