如何基于属性值实现数组元素N级自嵌套?Filter元素嵌套需求
实现数组元素的嵌套过滤逻辑
我有两个数组lenearArray和nestingForFilter,需要按照以下规则生成目标数组:
- 仅对
isParent = true的元素执行嵌套操作 - 需嵌套的元素要添加到父元素的
or属性中
代码示例
原数组定义:
let lenearArray: any[] = [ { filter: 'name', type: 'contains', isParent: true }, { filter: 'age', type: 'contains' }, { filter: 'gender', type: 'contains' }, { filter: 'address', type: 'contains' }]; let nestingForFilter: string[] = [ 'age', 'gender' ];
期望输出
let outputArray: any[] = [ { filter: 'name', type: 'contains', isParent: true, or: { filter: 'age', type: 'contains', or: { filter: 'gender', type:'contains' } } }, { filter: 'address', type: 'contains' } ]
解决方案
以下是符合需求的TypeScript实现代码:
const lenearArray: any[] = [ { filter: 'name', type: 'contains', isParent: true }, { filter: 'age', type: 'contains' }, { filter: 'gender', type: 'contains' }, { filter: 'address', type: 'contains' } ]; const nestingForFilter: string[] = ['age', 'gender']; // 构建嵌套的or结构 function buildNestedChain(filterNames: string[]) { return filterNames.reduceRight((prev, curr) => { const matchedItem = lenearArray.find(item => item.filter === curr); if (!matchedItem) return prev; // 如果有上一个嵌套元素,就给当前元素添加or属性 return prev ? { ...matchedItem, or: prev } : matchedItem; }, null); } // 生成最终输出数组 const outputArray = lenearArray.reduce((result, currentItem) => { if (currentItem.isParent) { const nestedChain = buildNestedChain(nestingForFilter); result.push({ ...currentItem, ...(nestedChain ? { or: nestedChain } : {}) }); } else if (!nestingForFilter.includes(currentItem.filter)) { // 不在嵌套列表里的元素直接加入结果 result.push(currentItem); } return result; }, [] as any[]); console.log(outputArray);
逻辑说明
buildNestedChain函数通过reduceRight从后往前遍历嵌套元素列表,逐个将元素嵌套到前一个元素的or属性中,最终生成完整的嵌套链- 遍历原数组时:
- 识别出
isParent=true的父元素,将构建好的嵌套链挂载到它的or属性后加入结果数组 - 跳过已经被嵌套的元素(即
nestingForFilter里的元素) - 其余未参与嵌套的元素直接加入结果数组
- 识别出
内容的提问来源于stack exchange,提问作者sumit sharma
相关产品推荐
相关产品推荐

