如何在JavaScript中将嵌套对象数组转换为键值对对象
把嵌套树状数组转换为指定键值对象的解决方案
嘿,这问题我熟!你需要把那个带id、name、parentId和children的树状数组,转换成以name为键、叶子节点值为null的嵌套对象对吧?咱们直接上代码,用递归的方式最适合处理这种层级结构。
首先先明确你的原始数据和目标结构:
原始树状数组
const tree = [ { "id": 1, "name": "Groceries", "parentId": null, "children": [ { "id": 3, "name": "Organic eggs", "parentId": 1, "children": [] }, { "id": 5, "name": "Fruits", "parentId": 1, "children": [ { "id": 6, "name": "Apple", "parentId": 5, "children": [] }, { "id": 7, "name": "Berries", "parentId": 5, "children": [ { "id": 8, "name": "Blueberry", "parentId": 7, "children": [] }, { "id": 9, "name": "Raspberry", "parentId": 7, "children": [] } ] } ] } ] } ];
目标简化对象
const simpleObject = { Groceries: { 'Organic eggs': null, Fruits: { Apple: null, Berries: { Blueberry: null, Raspberry: null } } } };
实现函数
咱们写一个递归函数来处理这个转换:
function convertTreeToSimpleObject(nodes) { const result = {}; nodes.forEach(node => { // 如果当前节点有子节点且子节点不为空,递归处理子节点 if (node.children && node.children.length > 0) { result[node.name] = convertTreeToSimpleObject(node.children); } else { // 叶子节点赋值为null result[node.name] = null; } }); return result; } // 调用函数(因为原始tree是数组,根节点在第一个元素) const convertedObject = convertTreeToSimpleObject(tree); console.log(convertedObject);
函数逻辑说明
- 遍历传入的节点数组,为每个节点创建对应的键(用节点的
name) - 检查节点的
children:如果有子节点且子数组不为空,就递归调用函数处理子节点,把返回的嵌套对象作为当前键的值 - 如果没有子节点(或者子数组为空),就把当前键的值设为
null - 最后返回组装好的对象
运行这段代码后,得到的convertedObject就和你想要的目标结构完全一致啦!如果你的树有多个根节点(原始数组有多个顶级元素),这个函数也能自动处理,把所有根节点都转换成对象的顶级键。
内容的提问来源于stack exchange,提问作者Csaba
相关产品推荐
相关产品推荐

