数组合并且去重&向一个数组添加一条数据(重复的就不添加)&数组对象去重处理

本文介绍了如何使用ES6的reduce方法合并两个数组并实现去重,同时讲解了在向表格添加数据时如何避免添加重复项。对于数组对象的去重问题,提出了采用间接方法解决的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两个结构相同的数组是可以合并的,使用es6的reduce方法可以合并两个数组并去重,例子如下:

将一个数组添加到另一个数组中并去重,其中tableData是将要
添加到fatherTablelist的数组,这时建议用es6的reduce方法:
    inChildByValue: function(tableData){
      if (this.fatherTablelist.length < 1 ) {
        this.fatherTablelist = tableData
        this.inInnerVisible = false
        this.$alert('实施信息新增成功!','信息提示',{
          confirmButtonText:'确定',
        })
      }else {
        // 合并两个数组
        let resources = [...this.fatherTablelist,...tableData]
        // 去重
        let temp = {}
        resources = resources.reduce((prev,curv) => {
          // 若临时对象中有一模一样的item,则什么都不做
          if (temp[curv.projImplementInst]&&temp[curv.authObject]){}
          else{
            temp[curv.projImplementInst] = true
            temp[curv.authObject] = true
            prev.push(curv)
          }
          return prev
        },[])
        console.log('resources',resources)
        this.fatherTablelist = resources
        this.inInnerVisible = false
      }
    },

参考教程:点这里

往一个table里面添加一条数据,如果重复则不添加,使用some函数很简单:

       let obj = {
          staffid:this.multipleSelectionPeoples[0].staffid,
          username:this.multipleSelectionPeoples[0].username,
          projTabencode:this.multipleSelectionSecrets[0].projTabencode,
          projTabcnname:this.multipleSelectionSecrets[0].projTabcnname
        }
        let len = this.tableData.length
        if(len === 0) {
          this.tableData.push(obj)
        }else {
         let res =  this.tableData.some(item => {
            return item.staffid === obj.staffid && item.projTabencode === obj.projTabencode
          })
          if(res) {
              this.$message({
                type: 'warning',
                message: '已存在重复数据'
              })
          } else {
            this.tableData.push(obj)
          }
        }

3.数组对象去重

一般的数组去重可以直接用 new Set() 方法即可,但是数组对象的话,比较复杂,不能直接用,我们可以采取间接的方法来去重

数组对象去重

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值