1 回答

TA貢獻(xiàn)1862條經(jīng)驗 獲得超6個贊
您可以創(chuàng)建一個解決方案,該解決方案將使用level屬性將當(dāng)前對象推送到嵌套結(jié)構(gòu)中的某個級別,并將其與引用和reduce方法結(jié)合起來。
const data = [{"code":"01","name":"Some name 1","level":"1"},{"code":"01.1","name":"Some name 2","level":"2"},{"code":"01.11","name":"Some name 3","level":"3"},{"code":"01.11.1","name":"Some name 4","level":"4"},{"code":"01.11.11","name":"Some name 5","level":"5"},{"code":"01.11.12","name":"Some name 6","level":"5"}]
const result = data.reduce((r, { level, ...rest }) => {
const value = { ...rest, children: [] }
r[level] = value.children;
r[level - 1].push(value)
return r;
}, [[]]).shift()
console.log(result)
添加回答
舉報