使用递归算法深度收集数据结构中的点位信息

这是一个递归遍历算法 ,能够从任意复杂的嵌套数据结构(对象或数组)中,自动提取并收集特定的点位信息。无论数据结构的层级有多深、结构多么复杂,该算法都能智能地遍历所有节点,找到并收集目标数据。

普通版本

javascript 复制代码
/**
 * 递归收集对象或数组中的所有点位信息
 * @param {Object|Array} data - 要遍历的数据结构
 * @param {Array} points - 收集到的点位数组(内部使用,调用时可省略)
 * @returns {Array} 包含所有点位信息的数组
 */
const collectPoints = (data, points = []) => {
    // 基础类型和null值直接返回
    if (!data || typeof data !== 'object') {
        return points;
    }

    // 处理数组
    if (Array.isArray(data)) {
        data.forEach(item => collectPoints(item, points));
        return points;
    }

    // 处理对象
    // 如果存在point属性,则收集该点位
    if (typeof data.point === 'string') {
        points.push({
            name: data.name || data.point,
            point: data.point
        });
    }

    // 递归遍历对象的所有属性值
    Object.values(data).forEach(value => {
        if (value && typeof value === 'object') {
            collectPoints(value, points);
        }
    });

    return points;
};

加强版本

javascript 复制代码
/**
 * 通用递归收集函数
 * @param {Object|Array} data - 要遍历的数据结构
 * @param {Object} options - 配置选项
 * @param {string} options.targetKey - 要收集的目标字段名
 * @param {string} [options.nameKey='name'] - 作为名称的字段名
 * @param {Array} collection - 收集到的数组(内部使用)
 * @returns {Array} 收集到的数据数组
 */
const collectDataRecursively = (data, options, collection = []) => {
    const { targetKey, nameKey = 'name' } = options;
    
    if (!data || typeof data !== 'object') {
        return collection;
    }

    if (Array.isArray(data)) {
        data.forEach(item => collectDataRecursively(item, options, collection));
        return collection;
    }

    // 收集目标字段
    if (data[targetKey] !== undefined) {
        collection.push({
            name: data[nameKey] || data[targetKey],
            value: data[targetKey]
        });
    }

    // 递归处理对象属性
    Object.values(data).forEach(value => {
        if (value && typeof value === 'object') {
            collectDataRecursively(value, options, collection);
        }
    });

    return collection;
};
相关推荐
Tian_Hang4 分钟前
Factory Method | 工厂方法
开发语言·c++
wearegogog12313 分钟前
基于MATLAB实现雷达RCS Swerling模型
开发语言·matlab
星梦清河34 分钟前
Java—异步编程
java·开发语言
接着奏乐接着舞1 小时前
dto 转entity方法
java·开发语言
0x00071 小时前
译 Anders Hejlsberg 谈 C# 与 .NET
开发语言·c#·.net
czhaii1 小时前
基于51单片机的Modbus从机通信系统
开发语言·单片机
elseif1231 小时前
【C++】vector 详细版
开发语言·c++·算法
codingPower1 小时前
JAVA后端安全进阶:基于HMAC-SHA256+Nonce+Timestamp的API防重放攻击方案
java·开发语言·spring boot·安全
暗冰ཏོ1 小时前
Go 语言从入门到后端项目实战完整指南
开发语言·后端·golang·go·go语言
Xin_ye100861 小时前
C# 零基础到精通教程 - 第十七章:前端集成——Blazor 基础
开发语言·c#