如何提取JavaScript对象层级键并按分支分组为二维数组?
提取嵌套JavaScript对象的层级键数组
给定如下嵌套结构的JavaScript对象:
const obj = { "test1": { "test12": "val1", "test13": { "test131": "val1", "test132": "val2" } }, "test2": "val2" }
需要提取出所有键,按顶层键分组,将每个顶层键及其所有嵌套子键整理为一维数组,最终得到如下格式的二维数组:
const keys = [["test1", "test12", "test13", "test131", "test132"], ["test2"]];
实现方案
可以通过递归遍历的方式完成需求,具体代码如下:
function extractNestedKeys(obj) { const result = []; // 遍历每个顶层键 for (const topKey of Object.keys(obj)) { const keyList = [topKey]; // 递归收集所有子键 function collectSubKeys(currentValue) { if (typeof currentValue === 'object' && currentValue !== null) { const subKeys = Object.keys(currentValue); keyList.push(...subKeys); subKeys.forEach(key => collectSubKeys(currentValue[key])); } } collectSubKeys(obj[topKey]); result.push(keyList); } return result; } // 测试使用 const obj = { "test1": { "test12": "val1", "test13": { "test131": "val1", "test132": "val2" } }, "test2": "val2" }; const keys = extractNestedKeys(obj); console.log(keys); // 输出目标格式的数组
逻辑说明
- 遍历对象的每个顶层键,为每个顶层键初始化一个包含自身的键数组
- 递归处理顶层键对应的值:若当前值是对象(且不为null),则提取该对象的所有子键加入数组,再继续遍历每个子键对应的值,重复收集操作
- 每个顶层键对应的键数组处理完成后,加入最终结果数组
额外说明
如果对象中存在不同层级的同名键,数组会包含重复项。若需要去重,可以将keyList的最终值替换为[...new Set(keyList)]。
内容的提问来源于stack exchange,提问作者Masoud Tesna
相关产品推荐
相关产品推荐

