1、实现效果
const list = [
{name: 'A', id: 1, desc: 'test'},
{name: 'B', id: 2, desc: 'test'},
{name: 'C', id: 3, desc: 'test'},
{name: 'D', id: 4, desc: 'test'},
{name: 'A', id: 5, desc: 'test'},
{name: 'C', id: 6, desc: 'test'},
{name: 'B', id: 7, desc: 'test'},
{name: 'B', id: 8, desc: 'test'},
{name: 'A', id: 9, desc: 'test'},
{name: 'D', id: 10, desc: 'test'},
]
[
{
"name": "A",
"id": 1,
"desc": "test",
"children": [
{"name": "A", "id": 1, "desc": "test"},
{"name": "A", "id": 5, "desc": "test"},
{"name": "A", "id": 9, "desc": "test"}
]
},
{
"name": "B",
"id": 2,
"desc": "test",
"children": [
{"name": "B", "id": 2, "desc": "test"},
{"name": "B", "id": 7, "desc": "test"},
{"name": "B", "id": 8, "desc": "test"}
]
},
{
"name": "C",
"id": 3,
"desc": "test",
"children": [
{"name": "C", "id": 3, "desc": "test"},
{"name": "C", "id": 6, "desc": "test"}
]
},
{
"name": "D",
"id": 4,
"desc": "test",
"children": [
{"name": "D", "id": 4, "desc": "test"},
{"name": "D", "id": 10, "desc": "test"}
]
}
]
2、代码实现
const list = [
{name: 'A', id: 1, desc: 'test'},
{name: 'B', id: 2, desc: 'test'},
{name: 'C', id: 3, desc: 'test'},
{name: 'D', id: 4, desc: 'test'},
{name: 'A', id: 5, desc: 'test'},
{name: 'C', id: 6, desc: 'test'},
{name: 'B', id: 7, desc: 'test'},
{name: 'B', id: 8, desc: 'test'},
{name: 'A', id: 9, desc: 'test'},
{name: 'D', id: 10, desc: 'test'},
]
let newList = []
list.forEach(item => {
let status = newList.find(el => el.name === item.name)
if (status) {
status.children.push({...item})
} else {
let obj = {...item, children: [{...item}]}
newList.push(obj)
}
})
console.log('newList', newList);