Example1 expects to convert to the following form:
const originData = ["1#12", "2#12", "3#13", "5#13", "4#13", "6#14"]; / / / / / {modeid: [1, 2], projectId: 12}, / / {modeid:,5,4 [3], projectId: 13}, // {modeid:[6],projectId:14} // ] function getList(list) { const temp = {}; return list.reduce((arr,val)=>{ const [mid, pid] = val.split("#"); if (temp[pid]) { temp[pid].push(mid); } else { temp[pid] = [mid]; arr.push({ projectId: pid, modelId: temp[pid], }); } return arr },[]) } getList(originData)Copy the code
Example2 is converted to a tree structure
const data = [ { id: 56, parentId: 62 }, { id: 81, parentId: 80 }, { id: 74, parentId: null }, { id: 76, parentId: 80 }, { id: 63, parentId: 62 }, { id: 80, parentId: 86 }, { id: 87, parentId: 86 }, { id: 62, parentId: 74 }, { id: 86, parentId: 74 }, ]; function arrayToTree(items) { const result = []; Const itemMap = {}; // for (const item of items) { const id = item.id; const pid = item.pid; if (! itemMap[id]) { itemMap[id] = { children: [], } } itemMap[id] = { ... item, children: itemMap[id]['children'] } const treeItem = itemMap[id]; if (pid === null) { result.push(treeItem); } else { if (! itemMap[pid]) { itemMap[pid] = { children: [], } } itemMap[pid].children.push(treeItem) } } return result; } arrayToTree(data)Copy the code
Object references are one of the most basic concepts in JavaScript, and the above two examples use references