将近2万5的平行结构数据,JavaScript怎么有更好性能来组合成树结构呢?

Mondo
  • 945

我使用下面来循环出数据后将近有23秒时间,有没有更好的方法来优化下感谢各位大佬

export async function getOrgTree(treeArray){
  let r = [];
  let tmpMap ={};
  for(let i = 0, len = treeArray.length; i < len; i++){   
    tmpMap[treeArray[i]['code']]= treeArray[i];
  }
  for(let i = 0, len = treeArray.length; i < len; i++){
    let key = tmpMap[treeArray[i]['parentCode']];
    
    if (key) {
      if (!key['children']) {
        key['children'] = [];
        key['children'].push(treeArray[i]);
      } else {
        if (key['children'].findIndex(v => v.code === treeArray[i].code) === -1) {
          key['children'].push(treeArray[i]);
        }
      }
      if(!treeArray[i]['parentCode']||treeArray[i]['parentCode']==='0'||treeArray[i]['parentCode']==='root'){
        r.push(treeArray[i]);
      }
    } else if (!treeArray[i]['parentCode']||treeArray[i]['parentCode']==='0'||treeArray[i]['parentCode']==='root'){
      r.push(treeArray[i]);
    }
  }
  return r;
}
回复
阅读 848
1 个回答
✓ 已被采纳

找到为什么这么久的原因了

if (key['children'].findIndex(v => v.code === treeArray[i].code) === -1) {
  key['children'].push(treeArray[i]);
}

由于这一句是要循环key['children']里面每个元素,而我们本不需要来循环每个元素,所以改为

if (key['children'].some(v => v.code !== treeArray[i].code)) {
  key['children'].push(treeArray[i]);
}

整个修改:

export async function getOrgTree(treeArray){
  let r = [];
  let tmpMap ={};
  for(let i = 0, len = treeArray.length; i < len; i++){
    tmpMap[treeArray[i]['code']]= treeArray[i];
  }
  for(let i = 0, len = treeArray.length; i < len; i++){
    let key = tmpMap[treeArray[i]['parentCode']];    
    if (key) {
      if (!key['children']) {
        key['children'] = [];
        key['children'].push(treeArray[i]);
      } else {
        if (key['children'].some(v => v.code !== treeArray[i].code)) {
          key['children'].push(treeArray[i]);
        }
      }
    } else{
      r.push(treeArray[i]);
    }
  }
  return r;
}

循环方式也是有性能的,for...of就要比for ... i++要慢,亲测这么2万多数据,慢了1秒

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏