使用 JS/lodash 按规则列表过滤深层嵌套数组

问题描述 投票:0回答:1

A 具有深层结构的报表传递表格。每种形式都有自己的格式,每种格式都有自己的频率。

 const forms = [
      {
        value: "1",
        label: 'Email',
        formats: [
          {
            value: '1',
            label: 'PDF',
            frequency: [
              {
                value: 'D',
                label: 'Daily',
              },
              {
                value: 'W',
                label: 'Weekly',
              },
            ],
          },
          {
            value: '2',
            label: 'XML',
            frequency: [
              {
                value: 'D',
                label: 'Daily',
              },
            ],
          },
        ],
      },
      {
        value: '2',
        label: 'Post',
        formats: [
          {
            value: '1',
            label: 'PDF',
            frequency: [
              {
                value: 'D',
                label: 'Daily',
              },
              {
                value: 'W',
                label: 'Weekly',
              },
            ],
          },
          {
            value: '2',
            label: 'XML',
            frequency: [
              {
                value: 'D',
                label: 'Daily',
              },
            ],
          },
        ],
      },
    ];

我还有另一个数组,其中包含表示表单结构的限制/规则的对象。现在我需要以某种方式循环每个选项并将其与这些限制进行比较。如果该选项与限制对象之一具有相同的值(形式、格式和频率),则该特定选项将从结构中删除,或者它将根据隐藏值保留在那里。我怎样才能实现它或者我应该使用什么策略?

const restrictions = [
  {form: '1', format: '1', frequency: 'D', hide: false},
  {form: '1', format: '2', frequency: 'W', hide: true},
  {form: '2', format: '1', frequency: 'D', hide: true},
  {form: '2', format: '2', frequency: 'W', hide: false},
]
javascript arrays json list lodash
1个回答
0
投票

您可以使用解构赋值来使代码紧凑:

const forms = [{"value":"1","label":"Email","formats":[{"value":"1","label":"PDF","frequency":[{"value":"D","label":"Daily"},{"value":"W","label":"Weekly"}]},{"value":"2","label":"XML","frequency":[{"value":"D","label":"Daily"}]}]},{"value":"2","label":"Post","formats":[{"value":"1","label":"PDF","frequency":[{"value":"D","label":"Daily"},{"value":"W","label":"Weekly"}]},{"value":"2","label":"XML","frequency":[{"value":"D","label":"Daily"}]}]}]

const restrictions = [
  {form: '1', format: '1', frequency: 'D', hide: false},
  {form: '1', format: '2', frequency: 'W', hide: true},
  {form: '2', format: '1', frequency: 'D', hide: true},
  {form: '2', format: '2', frequency: 'W', hide: false},
]

filteredForms = forms.map(({value: x, label, formats}) =>
  ({value: x, label, formats: formats.map(({value: y, label, frequency}) =>
      ({value: y, label, frequency: frequency.filter(({value: z}) =>
          restrictions.some(({form: xx, format: yy, frequency: zz, hide}) =>
            !hide && x===xx && y===yy && z===zz
))}))}))

console.log(filteredForms)

© www.soinside.com 2019 - 2024. All rights reserved.