用遞歸處理數據
阿新 • • 發佈:2018-02-07
stringify let 遞歸 post clas var ring each dir
var retrunArr = []; const arr = [ ["項目庫","餐飲","火鍋"], ["項目庫","餐飲","火大","火鍋"], ["項目庫1","餐飲","火大","火鍋"], ["項目庫1","餐飲","火大","火鍋"], ["項目庫2","餐飲","火大","火鍋"], ]; function di(pushArr, index, strArr) { let obj, exist = false; obj = { name: strArr[index], children: index== strArr.length - 1 ? null : [] } pushArr.forEach((o) => { if (o.name === strArr[index]) { obj = o; exist = true; } }); if (!exist) { pushArr.push(obj); }if (index < strArr.length - 1 && obj.children !== null) { di(obj.children, index + 1, strArr); } } arr.forEach((o, i) => { di(retrunArr, 0, arr[i]); }); console.dir(JSON.stringify(retrunArr)); /*[ { "name": "項目庫", "children": [ { "name": "餐飲", "children": [ { "name": "火鍋", "children": null }, { "name": "火大", "children": [ { "name": "火鍋", "children": null } ] } ] } ] }, { "name": "項目庫1", "children": [ { "name": "餐飲", "children": [ { "name": "火大", "children": [ { "name": "火鍋", "children": null } ] } ] } ] }, { "name": "項目庫2", "children": [ { "name": "餐飲", "children": [ { "name": "火大", "children": [ { "name": "火鍋", "children": null } ] } ] } ] } ]*/
用遞歸處理數據