過濾樹形結構數組的方法

前天做項目時候,遇到一個方法,過濾樹形數據,把符合條件的數據過濾出來,樹形數據如下:

const objarr= [{
				"id": 1,
				"isshow": true,
				"children": [{
					"id": 2,
					"isshow": true,
					"children": [{
						"id": 100268,
						"isshow": false,
						"showname": "ccccc",
						"name": "ccccc",
						"level": 3,
						"half": false
					}, {
						"id": 6,
						"isshow": true,
						"showname": "純純粹粹",
						"name": "純純粹粹",
						"level": 3,
						"half": false
					}, {
						"id": 100500,
						"isshow": true,
						"showname": "666",
						"name": "666",
						"level": 3,
						"half": false
					}],
					"showname": "1.1猜猜猜等到",
					"name": "1.1猜猜猜等到",
					"level": 2,
					"half": true
				}],
				"showname": "嗯哼",
				"name": "1",
				"level": 1,
				"half": true
			}, {
				"id": 3,
				"isshow": true,
				"children": [{
					"id": 4,
					"isshow": true,
					"showname": "2.1",
					"name": "2.1",
					"level": 2,
					"half": false
				}, {
					"id": 5,
					"isshow": true,
					"showname": "純純粹粹純純粹粹",
					"name": "純純粹粹純純粹粹",
					"level": 2,
					"half": false
				}],
				"showname": "2",
				"name": "2",
				"level": 1,
				"half": false
			}, {
				"id": 100121,
				"isshow": true,
				"children": [{
					"id": 100122,
					"isshow": true,
					"showname": "vvv v",
					"name": "vvv v",
					"level": 2,
					"half": false
				}],
				"showname": "單位名稱",
				"name": "單位名稱",
				"level": 1,
				"half": false
			}]

過濾出屬性isshow爲true的數據,處理上面數據,處理方法如下

convert (arr) {
      const newArr = arr.filter(item => item.isshow)
      return newArr.map(item => {
        if (item.children) {
          item.children = this.convert(item.children)
        }
        return item
      })
    }
    const arr = convert(objarr)
	簡單的方法就實現了
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章