javascript - 按月数过滤一系列产品
问题描述
我正在 vue 中做一个项目,我正在尝试从包含在数组中的对象数组的 json 中的产品列表中进行过滤。我有一个不同月份的选择器,可以按每个产品的月份数进行过滤,并且只显示包含这些月份的产品。
[
{
"active": true,
"installment": [
[
{
"product": "Ipad",
"months": 12,
"installment": 63.94
}
],
[
{
"product": "Ipad",
"months": 6,
"installment": 63.94
}
]
]
},
{
"active": true,
"installment": [
[
{
"product": "Iphone",
"months": 12,
"installment": 63.94
}
],
[
{
"product": "Iphone",
"months": 6,
"installment": 63.94
}
]
]
},
{
"active": true,
"installment": [
[
{
"product": "Mac",
"months": 18,
"installment": 63.94
}
]
]
}
]
这将是如果在月份选择器中我选择 12 个月我想获得的 json
[
{
"active": true,
"installment": [
[
{
"product": "Ipad",
"months": 12,
"installment": 63.94
}
]
]
},
{
"active": true,
"installment": [
[
{
"product": "Iphone",
"months": 12,
"installment": 63.94
}
]
]
}
]
我该怎么做?
解决方案
我相信有一种更优雅的方式,但这是一种方法:
var arr = [
{
"active": true,
"installment": [
[
{
"product": "Ipad",
"months": 12,
"installment": 63.94
}
],
[
{
"product": "Ipad",
"months": 6,
"installment": 63.94
}
]
]
},
{
"active": true,
"installment": [
[
{
"product": "Iphone",
"months": 12,
"installment": 63.94
}
],
[
{
"product": "Iphone",
"months": 6,
"installment": 63.94
}
]
]
},
{
"active": true,
"installment": [
[
{
"product": "Mac",
"months": 18,
"installment": 63.94
}
]
]
}
]
var result = arr.reduce((acc, curr) => {
if (curr.installment.flat().some(i => i.months == 12)) {
acc.push({
...curr,
installment: [curr.installment.flat().filter(i => i.months == 12)]
})
}
return acc
}, [])
console.log(result)
推荐阅读
- python - 引用自身的 Python 列表 - 它是如何工作的?
- notepad++ - Notepad ++中如何将一行数字分成多行
- python - 如何在熊猫数据框中居中标题文本?
- c - 循环链表中的分段错误
- asp.net-core-mvc - ASP.NET Core - FormAction 永远不会传入好方法
- pdf - 如何编辑交互式 PDF?
- c# - 将 C# 变量推送到 JavaScript 时出错
- python - 我该如何解决这个 AttributeError?
- angular - Angular 架构:如何使用多个 HTTP 服务处理状态持久性?
- ios - 使用 ContactsUI 快速获取所有联系电话号码