vue 将数组中利用indexOf去重相同名,将值合并一排的方法
<template> <div> <div v-for="(value,key) in userClass"> <span>{{ key}}</span> <span style="color: red">*</span> <span v-for="item in value">{{ item.phone}};</span> </div> </div> </template> <script> export default { name: "indexOfDemo", data() { return { userList: [ {name: '张三', phone: '13811111111'}, {name: '张三', phone: '13822222222'}, {name: '张三', phone: '13833333333'}, {name: '李四', phone: '13844444444'}, {name: '李四', phone: '13855555555'}, {name: '王五', phone: '13866666666'}, {name: '王五', phone: '13877777777'}, {name: '王五', phone: '13888888888'} ], } }, created() { }, computed: { userClass() { let typeList = []; //定义空数组,用于装载去重之后的数组, let userClass = {}; //定义空对象,用于数组转换成对象 if (this.userList) { //如果有值 this.userList.forEach(item => { //可以用indexOf()数组去重 如果检索的结果匹配到,则返回 1. 如果检索的结果没有匹配值,则返回 -1. if (typeList.indexOf(item.name) === -1) { typeList.push(item.name); userClass[item.name] = [item]; }else { userClass[item.name].push(item); } }) } console.log(userClass) return userClass; } } } </script> <style scoped> </style>
结果:
张三*13811111111;13822222222;13833333333;
李四*13844444444;13855555555;
王五*13866666666;13877777777;13888888888;