Vue.js 中如何避免数组添加重复数据 - 使用 key 字段进行去重
{"title":"Vue selectionRows数组中数据字段key是不重复的,但是可以多次赋值给this.mustMiddlegroundDifArr数组,如何避免this.mustMiddlegroundDifArr数组中数据不会重复,请给出完整代码内容:以下是一个示例代码,演示如何避免向数组中添加重复的数据:\n\njavascript\nexport default {\n data() {\n return {\n selectionRows: [\n { key: 1, value: 'A' },\n { key: 2, value: 'B' },\n { key: 3, value: 'C' }\n ],\n mustMiddlegroundDifArr: []\n };\n },\n methods: {\n addToMustMiddlegroundDifArr(row) {\n // 检查this.mustMiddlegroundDifArr数组是否已经包含了相同的key值\n const isDuplicate = this.mustMiddlegroundDifArr.some(item => item.key === row.key);\n if (!isDuplicate) {\n this.mustMiddlegroundDifArr.push(row);\n }\n }\n }\n};\n\n\n在这个示例中,我们使用Array.prototype.some()方法来检查this.mustMiddlegroundDifArr数组中是否已经包含了相同的key值。只有当this.mustMiddlegroundDifArr数组中不存在相同的key值时,才将row添加到this.mustMiddlegroundDifArr数组中。这样就可以确保this.mustMiddlegroundDifArr数组中的数据不会重复。
原文地址: https://www.cveoy.top/t/topic/qlCl 著作权归作者所有。请勿转载和采集!