1. 程式人生 > 其它 >js 陣列物件樹形 遞迴過濾

js 陣列物件樹形 遞迴過濾

在專案開發過程中遇到,需要遞迴過濾的樹形物件陣列,

上程式碼:

這是我的表格頭資料,我需要通過點選一個select下拉框分別顯示含稅、不含稅、全部顯示的表頭,後端就一個介面預設返回所有的資料,這時候就需要前端來通過動態修改表頭實現

 column: [
                    {label: '科目編碼', prop: 'subjectCode', width: '142px'},
                    {label: '科目名稱', prop: 'subjectName', width: '140px'},
                    {
                        label:
'總成本(含稅)', children:[ { label: '目標成本', prop: 'totalTargetCostTax', width: '120px', }, { label: '動態成本', prop: 'totalDynamicCostTax', width: '120px', }, { label: '目標建築單方', prop: 'totalUnilateralConstructionTax', width: '140px', }, { label:
'動態建築單方', prop: 'totalDynamicConstructionTax', width: '140px', }, { label: '動態可售單方', prop: 'totalDynamicSellTax', width: '140px', }, ] }, { label:
'總成本(不含稅)', children:[ { label: '目標成本', prop: 'totalTargetCost', width: '120px',}, { label: '動態成本', prop: 'totalDynamicCost', width: '120px', }, { label: '目標建築單方', prop: 'totalUnilateralConstruction', width: '140px', }, { label: '動態建築單方', prop: 'totalDynamicConstruction', width: '140px', }, { label: '動態可售單方', prop: 'totalDynamicSell', width: '140px', }, ] }, ]

由於我這表格是樹型結構的,我不知道有幾層,所以需要用到遞迴,過濾需要有判讀條件,當時只想到 includes方法判斷有沒有 ‘含稅’ 或者 ‘不含稅’來過濾返回相應的column資料

所以就是

  // 遞迴過濾
    switchDataVersonName(column, text){
      // column 是表格資料, text是判斷是否是含稅
// 先過濾第一層
     let newColumn = column.filter(item => !item.label.includes(text))
    // 得到新的陣列,但只是第一層的過濾,需要再次迴圈然後 判斷有children的時候 在呼叫一次本函式 傳入 x.children,還有判斷條件 newColumn.forEach(x
=> x.children && (x.children = this.switchDataVersonName(x.children, text)))
    // 最後把新陣列 return 出去
return newColumn },

1、傳入不含稅就顯示含稅的 表格表頭

2、傳入含稅就顯示不含稅的 表格表頭

3、全部就不用這個過濾函式直接返回原來表格表頭

然後就是實現了