現在有以下資料結構:
[{
id: 1,
pid: 0,
name: "年级"
}, {
id: 2,
pid: 1,
name: "一年级"
}, {
id: 3,
pid: 1,
name: "二年级"
}, {
id: 4,
pid: 0,
name: "专业"
}, {
id: 5,
pid: 4,
name: "单片机开发"
}]
寫一個JS方法,將其轉換成以下格式資料:
[{
id: 1,
pid: 0,
name: "年级",
children: [{
id: 2,
pid: 1,
name: "一年级"
}, {
id: 3,
pid: 1,
name: "二年级"
}]
}, {
id: 4,
pid: 0,
name: "专业",
children: [{
id: 5,
pid: 4,
name: "单片机开发"
}]
}]
某草草2017-06-28 09:29:56
參考一下
var sortedData = data.reduce((result, item) => {
result[item.id] = Object.assign({}, item)
return result
}, [])
var result = sortedData.reduce((result, item) => {
if (item.pid === 0) {
result.push(item)
} else {
if (sortedData[item.pid].children) {
sortedData[item.pid].children.push(item)
} else {
sortedData[item.pid].children = [item]
}
}
return result
}, [])