The set method realizes deduplication of object arrays

1. Target effect

        (1) Initial form data

         (2) Click the Add Data button, the table displays the data, add the same data here.

         (3) Click the Add Data button, the table displays the data, and add different data here.

2. Principle

       Knowledge points: set, map traversal, json.stringify and json.parse, array merging, rest destructuring assignment

(1) To judge whether the two basic types are the same, the value is compared. To judge whether two reference types are the same, the reference is compared.

(2) Set cannot deduplicate the objects in the array. The principle of set deduplication is to judge whether the memory unit positions of the two are the same, and only when the positions are the same can deduplication be performed. Basic types of data are all on the stack, so as long as the values ​​are the same, they can be deduplicated directly. Reference types are stored in the heap, and reference types with the same value and different locations cannot be deduplicated.

  (3) As long as the reference type data is converted into a basic data type, then you can use set to deduplicate. This case uses this idea to convert the object into a json string through JSON.stringify, and JSON.parse converts the json string into JSON object.

Three, practical operation

        (1) template template in App.vue

<template>
  <div id="app">
    <el-button type="primary" @click="addData()">添加数据</el-button>
<el-table
    :data="tableData"
    border
    stripe>
    <el-table-column
      prop="date"
      label="日期">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名">
    </el-table-column>
    <el-table-column
      prop="address"
      label="地址">
    </el-table-column>
  </el-table>
  </div>
</template>

        (2) script in App.vue

export default {
  name: 'App',
  data(){
    return {
      //表格数据
      tableData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 路'
        }],

      //模拟数据
      mockData:[{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 路'
        }]
    }
  },
  methods:{
    addData(){
        //将表格数据与模拟数据两个数组合并
        let newTable=this.tableData.concat(this.mockData)

        //表格数据去重
        this.tableData= [...new Set(newTable.map(item=>JSON.stringify(item)))].map(i=>JSON.parse(i))
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_42375707/article/details/125771071