treeSeparate.js 1.65 KB
export function treeSeparate(arry, condition, key) {
  let tree = [];
  arry.map(item => {
    let treeItem = {};
    treeItem['title'] = item.name;
    treeItem['key'] = item.id;
    Boolean(key) ? treeItem['value'] = item[key] : treeItem['value'] = item.id;
    (function cycle(childs, data){
      if (childs && childs.length > 0) {
        data['children'] = [];
        childs.map(child => {
          let childData = {};
          childData['title'] = child.name;
          childData['key'] = child.id;
          Boolean(key) ? childData['value'] = child[key] : childData['value'] = child.id;
          childData['children'] = [];
          cycle(child[condition], childData);
          data['children'].push(childData)
        })
      }
    })(item[condition], treeItem);
    tree.push(treeItem)
  });
  return tree
}

export function branchSeparate(arry, condition, key, title) {
  let tree = [];
  arry.map(item => {
    let treeItem = {};
    Boolean(title) ? treeItem['title'] = item[title] : treeItem['title'] = item.name;
    Boolean(key) ? treeItem['key'] = item[key] : treeItem['key'] = item.id;
    (function cycle(childs, data){
      if (childs && childs.length > 0) {
        data['children'] = [];
        childs.map(child => {
          let childData = {};
          Boolean(title) ? childData['title'] = child[title] : childData['title'] = child.name;
          Boolean(key) ? childData['key'] = child[key] : childData['key'] = child.id;
          childData['children'] = [];
          cycle(child[condition], childData);
          data['children'].push(childData)
        })
      }
    })(item[condition], treeItem);
    tree.push(treeItem)
  });
  return tree
}