# 求助，一道前端算法题，应该和递归有关

``````[
{
"name":"a1",
"val":"a1",
"level":1,
"son":[
{
"name":"a11",
"val":"a11",
"level":2,
"son":[
{
"name":"a111",
"val":"a111",
"level":3,
"son":[

]
}
]
}
]
},
{
"name":"b1",
"val":"b1",
"level":1,
"son":[
{
"name":"b11",
"val":"b11",
"level":2,
"son":[
{
"name":"b111",
"val":"b111",
"level":3,
"son":[

]
}
]
},
{
"name":"b12",
"val":"b12",
"level":2,
"son":[
{
"name":"b121",
"val":"b121",
"level":3,
"son":[

]
}
]
}
]
}
]``````
``````[
{
"name":"a1",
"val":"a1",
"level":1,
"son":[
{
"name":"a11",
"val":"a11",
"level":2,
"son":[
{
"name":"a111",
"val":"a111",
"level":3,
"son":[

]
},
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
},
{
"name":"全部",
"val":"",
"level":2,
"son":[
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
}
]
},
{
"name":"b1",
"val":"b1",
"level":1,
"son":[
{
"name":"b11",
"val":"b11",
"level":2,
"son":[
{
"name":"b111",
"val":"b111",
"level":3,
"son":[

]
},
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
},
{
"name":"b12",
"val":"b12",
"level":2,
"son":[
{
"name":"b121",
"val":"b121",
"level":3,
"son":[

]
},
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
},
{
"name":"全部",
"val":"",
"level":2,
"son":[
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
}
]
},
{
"name":"全部",
"val":"",
"level":1,
"son":[
{
"name":"全部",
"val":"",
"level":2,
"son":[
{
"name":"全部",
"val":"",
"level":3,
"son":[

]
}
]
}
]
}
]``````

2 个回答

``````function addAmountNode(nodes, level = 1) {
if (!nodes.length) {
return;
}
const son = nodes
.map(it => addAmountNode(it.son, level + 1))
.filter(it => it)
.slice(0, 1);
const amountNode = {
name: "全部",
val: "",
level,
son
};
nodes.push(amountNode);
return JSON.parse(JSON.stringify(amountNode));
}

console.log(JSON.stringify(data, null, 2));``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进