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

问题描述

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

我该怎么做?

标签: javascriptarraysjsonfilter

解决方案


我相信有一种更优雅的方式,但这是一种方法:

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)


推荐阅读