判断一个数组对象中是否已经具有该对象----利用JSON.stringify()

需求:判断一个数组中是否有该对象,如果有则提示已存在,没有则添加

原理:includes()方法可以判断一个数组中是否有该项,但是对于引用类型数据,需要进行深复制,否则判断得到的值永远都是false

  

基础代码:

    let arr = [1, 2, 3]

    console.log(arr.includes(1)) // true
    console.log(arr.includes(0)) // false

    let arr1=[
      {name:'xiaoming',age:20},
      {name:'sunyizhen',age:18}
    ]


    console.log(arr1.includes({name:'xiaoming',age:20})) // false
    console.log(JSON.stringify(arr1).includes(JSON.stringify({name:'xiaoming',age:20}))) // true
    console.log(JSON.stringify(arr1).includes(JSON.stringify({age:20,name:'xiaoming'}))) // false

应用场景:

导出字段添加至转换字段,同一个字段不能添加两次:

      if (JSON.stringify(this.conversionList).includes(JSON.stringify(item)))
        return this.$message.warning('不可重复添加')
      this.conversionList.push(item)

同一个对象只能添加一次到table中:

      if (JSON.stringify(this.tableData).includes(JSON.stringify(newObj)))
        return this.$message.error('单位转换列表中已存在该项')
      this.tableData.push(newObj)

注意:

  这种方式要求对象键值对按原有顺序排列,顺序不对结果也是返回false,以上表达的意思是includes()判断数组是否具有某一项时要注意引用类型数据的特殊处理。

原文地址:https://www.cnblogs.com/wuqilang/p/14001185.html