javascript - 按月过滤一系列产品
问题描述
我在 vue 中做一个项目,我有一个带有数组的 json 数组。我想制作一个月份过滤器,在我选择的月份中显示带有该过滤器的产品列表
而且我有一个几个月的选择器(6、12、18) 我怎样才能只显示我用选择器选择的产品?
[
{
"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
}
],
[
{
"product": "Mac",
"months": 24,
"installment": 63.94
}
]
]
}
]
解决方案
您可以遍历数组,然后将传递条件的元素推送到新数组,它看起来像这样
const array = [
{
"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
}
],
[
{
"product": "Mac",
"months": 24,
"installment": 63.94
}
]
]
}
]
let res = [];
// const filter = (y) => y.months == 6;
// if you have multiple filters
const filter = (y) => [6, 12, 18].includes(y.months);
array.forEach(x => {
x.installment.forEach(y => {
y[0].active = x.active;
if (filter(y[0])) res = [...res, ...y];
})
})
console.log(res);
推荐阅读
- group-by - 如何检查某些值是否超过阈值超过 n 天?
- python - 将图像从 Flask 发送到 React
- aggregation-framework - 不支持聚合阶段:'$bucket'
- python - 设置运行长度编码长度的最小限制
- sql - SSIS。如何将具有 nvarchar(max) 类型的列的表中的数据保存到原始文件目标
- python - 如何使用 Python REST API 执行 R 机器学习模型?
- java - 用 VFS 实现“移动”功能
- c# - EF Core 删除多对多关系中的数据
- java - 如何在 java Stream API 中对对象进行类型转换?
- php - 使用 PHP 转换器将 XML 转换为 CSV [图像抓取问题]