<script> var list = [ { type: 1, cat: "F1", class: "white", total: 12 }, { type: 1, cat: "F2#1", class: "white", total: 12 }, { type: 1, cat: "F2#2", class: "white", total: 12 }, { type: 1, cat: "F2#3", class: "white", total: 12 }, { type: 1, cat: "F3", class: "white", total: 12 }, { type: 1, cat: "F4", class: "white", total: 12 }, { type: 1, cat: "F1", class: "black", total: 12 }, { type: 1, cat: "F2#1", class: "black", total: 12 }, { type: 1, cat: "F2#2", class: "black", total: 12 }, { type: 1, cat: "F2#3", class: "black", total: 12 }, { type: 1, cat: "F3", class: "black", total: 12 }, { type: 1, cat: "F4", class: "black", total: 12 }, { type: 2, cat: "F1", class: "white", total: 12 }, { type: 2, cat: "F2#1", class: "white", total: 12 }, { type: 2, cat: "F2#2", class: "white", total: 12 }, { type: 2, cat: "F2#3", class: "white", total: 12 }, { type: 2, cat: "F3", class: "white", total: 12 }, { type: 2, cat: "F4", class: "white", total: 12 }, { type: 2, cat: "F1", class: "black", total: 12 }, { type: 2, cat: "F2#1", class: "black", total: 12 }, { type: 2, cat: "F2#2", class: "black", total: 12 }, { type: 2, cat: "F2#3", class: "black", total: 12 }, { type: 2, cat: "F3", class: "black", total: 12 }, { type: 2, cat: "F4", class: "black", total: 12 }, ]; function search_param(arr, key, val) { for (let index in arr) { if (key in arr[index] && arr[index][key] == val) { return index; } } return -1; } const res = []; for (let i in list) { const index_type = search_param(res, "type", list[i]["type"]); if (index_type == -1) { res.push({ type: list[i]["type"], cat: [ { sub_cat: list[i]["cat"], total: list[i]["total"], data: [ { class: list[i]["class"], }, ], }, ], }); } else { const index_sub_cat = search_param(res[index_type]["cat"], "sub_cat", list[i]["cat"]); if (index_sub_cat == -1) { res[index_type]["cat"].push({ sub_cat: list[i]["cat"], total: list[i]["total"], data: [ { class: list[i]["class"], }, ], }); } else { res[index_type]["cat"][index_sub_cat]["total"] += list[i]["total"]; res[index_type]["cat"][index_sub_cat]["data"].push({ class: list[i]["class"], }); } } } console.log(res); </script>
标签:重组,12,复杂,index,js,cat,total,type,class From: https://www.cnblogs.com/caroline2016/p/16921143.html