首页 > 解决方案 > 按月过滤一系列产品

问题描述

我在 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
            }
          ]
        ]
      }
    ]

标签: javascriptjson

解决方案


您可以遍历数组,然后将传递条件的元素推送到新数组,它看起来像这样

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);


推荐阅读