提问人:Vít Paník 提问时间:10/14/2023 更新时间:10/14/2023 访问量:44
使用 JS/lodash 按规则列表过滤深度嵌套数组
Filter deep nested array by list of rules with JS/lodash
问:
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},
]
答:
1赞
Andrew Parks
10/14/2023
#1
您可以使用解构赋值来使代码紧凑:
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)
评论
frequency
obj.frequency = obj.frequency.filter(...)
restrictions.some()