1. /**
    2. *
    3. * @param {Array} arrs 树形数据
    4. * @param {string} childs 树形数据子数据的属性名,常用'children'
    5. * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)
    6. * @returns
    7. */
    8. function extractTree(arrs,childs,attrArr){
    9. let attrList = [];
    10. if(!Array.isArray(arrs)&&!arrs.length)return [];
    11. if(typeof childs !== 'string')return [];
    12. if(!Array.isArray(attrArr)||Array.isArray(attrArr)&&!attrArr.length){
    13. attrList = Object.keys(arrs[0]);
    14. attrList.splice(attrList.indexOf(childs), 1);
    15. }else{
    16. attrList = attrArr;
    17. }W
    18. let list = [];
    19. const getObj = (arr)=>{
    20. arr.forEach(function(row){
    21. let obj = {};
    22. attrList.forEach(item=>{
    23. obj[item] = row[item];
    24. });
    25. list.push(obj);
    26. if(row[childs]){
    27. getObj(row[childs]);
    28. }
    29. })
    30. return list;
    31. }
    32. return getObj(arrs);
    33. }
    1. const arr = extractTree(list,'childs',['id'])

    1648170924019_7AE2F50A-C464-4db7-B50A-5F7EAB7FAB41.png