You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于属性值实现数组元素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);

逻辑说明

  1. buildNestedChain函数通过reduceRight从后往前遍历嵌套元素列表,逐个将元素嵌套到前一个元素的or属性中,最终生成完整的嵌套链
  2. 遍历原数组时:
    • 识别出isParent=true的父元素,将构建好的嵌套链挂载到它的or属性后加入结果数组
    • 跳过已经被嵌套的元素(即nestingForFilter里的元素)
    • 其余未参与嵌套的元素直接加入结果数组

内容的提问来源于stack exchange,提问作者sumit sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:50:36