JS vue中处理数据重复
- ant组件使用树形表格的时候,由于后台数据重复,查询报错索引重复 利用去重解决
- id 不唯一
<!--VUE代码-->
<!-- 根据 categoryBirdData table数据 取ID 回显到 tree 中-->
<a-tree
class="a-tree"
v-model="selectedKeys"
@check="onCheckTree"
checkable
:expanded-keys="expandedKeys"
@select="clickTreeTabTow"
:tree-data="gData"
:checkedKeys="selectedKeys"
@expand="onExpand"
:replace-fields="{
children: 'children',
key: 'id',
title: 'categoryNameCn',
}"
>
</a-tree>
<!-- 渲染表格数据 树形表格 -->
<a-table
:data-source="categoryBirdData"
rowKey="id"
:pagination="false"
bordered
show-size-changer
:loading="bindLoadingData"
>
</a-table>
methods:{
//根据HSCode ID查询
selCateList() {
let reqObj = {
id: this.selectedRowKeys[0],
}
if (this.selectedRowKeys.length !== 0) {
this.bindLoadingData = true
selCategoryBirdData(reqObj).then((res) => {
this.categoryBirdData = treeCovert(res.data, {
children: 'childList',
})
/*---------------------------数据去重 start ----------------------------- */
let arr = [] //临时存放的所有数据
this.categoryBirdData.forEach((item) => {
let newData = this.unique(item.children) //子数据去重
item.children = newData //将子数据去重重新赋值到父级的children
arr.push(item) //将去重后的数据放到 arr 数组中
})
this.categoryBirdData = arr //将去重后的数据赋值给table数据源
/*--------------------------- 数据去重 end ----------------------------- */
let defkey = [] // id存放的数组
res.data.forEach((item) => {
this.getRighttree(item, defkey)
})
this.selectedKeys = defkey //tree控件回显
this.bindLoadingData = false
})
}
},
//去重函数
unique(arr) {
const res = new Map()
return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
},
}
以上去重的是子类数据,如果想去重父类数据直接调用去重函数即可
如:
/*---------------------------数据去重 start ----------------------------- */
let arr = [] //临时存放的所有数据
this.categoryBirdData.forEach((item) => {
let newData = this.unique(item) //去重父级数据
arr.push(item) //将去重后的数据放到 arr 数组中
})
this.categoryBirdData = arr //将去重后的数据赋值给table数据源
/*--------------------------- 数据去重 end ----------------------------- */