js对象引用在数组中应用

126 阅读1分钟

example1 期望转换成下面的形式:

const originData = ["1#12", "2#12", "3#13", "5#13", "4#13", "6#14"];

//[
    //    {modeid:[1,2],projectId:12},
    //    {modeid:[3,5,4],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)  
    

example2 转换成树形结构

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)

对象引用是 JavaScript 中最基本的概念之一,上面俩个例子也是应用了引用这个知识点