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