请问大家，这个小算法问题，怎么改？

• 11

[

``````{
"categoryId": "373",
"parentId": "3",
"categoryName": "张三",
"sunCategorys": [
{
"categoryId": "374",
"parentId": "373",
"categoryName": "张三一",
},
{
"categoryId": "375",
"parentId": "373",
"categoryName": "张三二",
}
]
},
{
"categoryId": "374",
"parentId": "3",
"categoryName": "李四",
"sunCategorys": [
{
"categoryId": "375",
"parentId": "374",
"categoryName": "李四一",
},
{
"categoryId": "376",
"parentId": "374",
"categoryName": "李四二",
}
]
}``````

]

[

``````{
"text": "张三",
"children": [
{
"text": "张三一",
"id": 374
},
{
"text": "张三二",
"id": 375
}
]
},
{
"text": "李四",
"children": [
{
"text": "李四一",
"id": 375
},
{
"text": "李四二",
"id": 376
}
]
}``````

]

3 个回答

``var list = [{"categoryId": "373", "parentId": "3", "categoryName": "张三", "sunCategorys": [{"categoryId": "374", "parentId": "373", "categoryName": "张三一",}, {"categoryId": "375", "parentId": "373", "categoryName": "张三二",}]}, {"categoryId": "374", "parentId": "3", "categoryName": "李四", "sunCategorys": [{"categoryId": "375", "parentId": "374", "categoryName": "李四一",}, {"categoryId": "376", "parentId": "374", "categoryName": "李四二",}]}]``
``````function toTree(list = []) {
return list.map(function (item) {
return {
id: item.categoryId,
text: item.categoryName,
children: toTree(item.sunCategorys || [])
}
})
}

toTree(list);``````

es6写法

``````let toTree = (list = []) => list.map(({categoryId, categoryName, sunCategorys}) => ({
id: categoryId,
text: categoryName,
children: toTree(sunCategorys || [])
}));
toTree(list);``````

``````let rel = {'categoryId': 'id', 'categoryName': 'text', 'sunCategorys': 'children'};
JSON.parse(JSON.stringify(list), function (k, v) {
if (Object.keys(rel).includes(k)) {
this[rel[k]] = v;//根据映射修改key
} else if (typeof v == 'object') {
return v;//数组和对象返回原始值
}
});``````