如何在JavaScript中编写通用函数从嵌套对象提取指定格式数据
提取嵌套Buckets层级Key与最终Doc Count的通用函数
需求说明
给定包含多层嵌套buckets数组的聚合数据(嵌套层级预先知晓),需要提取每一层的key值,并保留最后一层的doc_count,最终输出扁平化的数组列表。
示例输入数据
const obj= { "aggregations": { "1": { "buckets": [ { "2": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 3171, "buckets": [ { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "demo_gg", "doc_count": 856 } ] }, "key": "/hello", "doc_count": 8888 }, { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "bye", "doc_count": 414 } ] }, "key": "added*", "doc_count": 4987 }, { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "nothere", "doc_count": 118 } ] }, "key": "/festive.txt", "doc_count": 1888 } ] }, "key": "200", "doc_count": 4771 }, { "2": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 536, "buckets": [ { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "dimension", "doc_count": 1435 } ] }, "key": "/auto/auto.xml", "doc_count": 1888 }, { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "cartoon", "doc_count": 34 } ] }, "key": "/.env", "doc_count": 888 }, { "3": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": "mouse", "doc_count": 8 } ] }, "key": "/form/admin/login", "doc_count": 888 } ] }, "key": "404", "doc_count": 2052 } ] } } }
期望输出结果
[ ['200', '/hello', 'demo_gg', 856], ['200', 'added*', 'bye', 414], ['200', '/festive.txt', 'nothere', 118], ['404', '/auto/auto.xml', 'dimension', 1435], ['404', '/.env', 'cartoon', 34], ['404', '/form/admin/login', 'mouse', 8] ]
通用解决方案代码
function extractNestedBuckets(data, levelCount) { const result = []; // 递归遍历函数 function traverse(buckets, currentPath) { for (const bucket of buckets) { // 收集当前层的key const newPath = [...currentPath, bucket.key]; // 获取下一层的聚合对象(比如第一层是"1",第二层是"2",以此类推) const nextLevelKey = String(currentPath.length + 1); const nextAgg = bucket[nextLevelKey]; if (currentPath.length === levelCount - 1) { // 到达最后一层,取最内层buckets的doc_count for (const innerBucket of nextAgg.buckets) { result.push([...newPath, innerBucket.key, innerBucket.doc_count]); } } else { // 未到最后一层,继续递归遍历下一层buckets traverse(nextAgg.buckets, newPath); } } } // 从第一层buckets开始遍历 const firstLevelAgg = data.aggregations["1"]; traverse(firstLevelAgg.buckets, []); return result; } // 使用示例:当前层级为3层,调用函数 const output = extractNestedBuckets(obj, 3); console.log(output);
代码逻辑说明
- 递归遍历核心:通过递归函数
traverse逐层处理buckets数组,每一层收集当前的key到路径数组中。 - 层级判断:根据传入的
levelCount判断是否到达倒数第二层,此时遍历最内层buckets,将完整路径+key+doc_count推入结果数组。 - 动态层级适配:通过
currentPath.length + 1动态获取下一层的聚合键(如"1"、"2"、"3"),适配任意预先指定的嵌套层级。
内容的提问来源于stack exchange,提问作者user16704275
相关产品推荐
相关产品推荐

