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

如何从深度嵌套数据结构中实现白名单式属性选择性复制?

实现支持嵌套对象的白名单属性选择

你当前的optionallySelProperties只能处理平级字段的筛选,没法递归处理嵌套对象或数组内的子属性选择。要解决这个问题,我们可以把白名单改成支持嵌套结构的配置,再通过递归遍历实现深层精准筛选。

1. 定义嵌套白名单结构

白名单采用对象结构,每个键对应要保留的字段:

  • 如果字段值设为true,表示直接保留该平级字段
  • 如果字段值是对象/数组,表示要对该嵌套字段(或数组元素)进行深层筛选,值就是对应的子白名单

针对你提供的目标数据,对应的嵌套白名单可以这样定义:

const whitelist = {
  productId: true,
  time: true,
  member: {
    teamMembers: [{
      name: true
    }]
  },
  plan: {
    id: true,
    lastModifiedDate: true,
    planDetails: {
      planName: true,
      status: true,
      customproductAllocations: [{
        allocationDetail: {
          dollar: true,
          allocations: [{
            name: true
          }]
        }
      }],
      products: {
        inital: true,
        externalproducts: [{
          name: true
        }],
        productAllocation: {
          productAllocation: [{
            category: true
          }]
        }
      },
      analysis: {
        analysisA: {
          key: true
        },
        analysisB: {
          key: true
        }
      }
    }
  }
};

2. 实现递归筛选函数

编写递归函数,根据嵌套白名单遍历数据,只保留指定字段:

import { isObject, isArray } from 'lodash';

const pickNested = (data: any, whitelist: any): any => {
  if (!data) return {};

  // 处理数组:遍历每个元素,用子白名单筛选
  if (isArray(data)) {
    return data.map(item => pickNested(item, whitelist[0]));
  }

  // 处理对象:遍历白名单键,递归筛选嵌套字段
  return Object.entries(whitelist).reduce((result, [key, config]) => {
    const value = data[key];
    if (value === undefined) return result;

    result[key] = (isObject(config) || isArray(config)) 
      ? pickNested(value, config) 
      : value;

    return result;
  }, {} as any);
};

函数说明

  • 兼容空数据:如果传入的data为空,直接返回空对象
  • 数组处理:自动遍历数组内的每个元素,用白名单中对应的子配置筛选
  • 嵌套处理:遇到嵌套对象/数组时,递归调用自身完成深层筛选
  • 可选字段兼容:如果数据中不存在白名单指定的字段,会自动跳过,不会添加到结果中

3. 使用示例

直接调用函数即可得到符合要求的筛选结果:

const copiedData = pickNested(data, whitelist);

生成的copiedData会严格保留你标注的所有字段,包括嵌套层级的指定属性,完全遵循白名单策略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 23:55:24