数组格式如下:
"industrySceneList": [{"mainIndustry": 1,"mainIndustryName": "林草","sceneList": [{"subIndustry": 1,"subIndustryName": "森林防火"}]},{"mainIndustry": 2,"mainIndustryName": "国土","sceneList": [{"subIndustry": 141,"subIndustryName": "其它-1"},{"subIndustry": 11,"subIndustryName": "耕地保护"},{"subIndustry": 12,"subIndustryName": "矿山保护"}]},{"mainIndustry": 12,"mainIndustryName": "其它-2","sceneList": [{"subIndustry": 71,"subIndustryName": "其它-3"}]}
],
第一种办法:通过map计数来判定:
onSubIndustryChange(industrySceneList) {let validIndust = true;let subIndustry = "";// 创建一个Map来存储subIndustry及其出现次数const subIndustryCounts = new Map();// 遍历industrySceneListindustrySceneList.forEach(industryScene => {// 遍历当前场景列表中的sceneListindustryScene.sceneList.forEach(scene => {// 获取当前subIndustryName的计数,如果不存在则默认为0const count = subIndustryCounts.get(scene.subIndustryName) || 0;// 将计数加1subIndustryCounts.set(scene.subIndustryName, count + 1);});});// 筛选出计数大于1的subIndustry,即重复的subIndustryconst duplicates = Array.from(subIndustryCounts).filter(([subIndustry, count]) => count > 1).map(([subIndustry, _]) => subIndustry);//数组转String用逗号拼接subIndustry = duplicates.join(',');if (duplicates.length > 0) {validIndust = false;this.$message({message: '当前存在' +subIndustry+'重复,请检查后重试',type: 'error'});}return validIndust;
},
第二种办法:通过ES6 set数据类型
hasDuplicateIds(value) {console.log(value);let dupValid = true;const nonMinusOneItems = this.industryScenario.filter(item => item.mainIndustry == value);const uniqueNonMinusOneIds = new Set(nonMinusOneItems.map(item => item.mainIndustry));if(nonMinusOneItems.length !== uniqueNonMinusOneIds.size){this.$message({message: '行业不能重复',type: 'error'});dupValid = false;}return dupValid;
},
---------- 兄弟们更喜欢哪一种呢~