在vue使用
<template>
<div @click="incident">
合并
</div>
</template>
<script>
export default {
data() {
return {
obj: [
{ name: "张三", age: 19 },
{ name: "李四", age: 1 },
{ name: "张三", age: 10 },
],
};
},
methods: {
sortArr(arr, str) {
var _arr = [] //最终的二维数组
//取出所有要合并的属性名
let strArr = arr.map(item=>{
return item[str]
})
//对属性名进行一次去重
strArr = Array.from(new Set(strArr))
//先遍历属性名数组
strArr.map(strItem =>{
let temporaryArr = []
//遍历所有的数组
arr.forEach((objectItem)=>{
//如果 strItem 和数组中的属性名相同就push进临时数组
if(strItem == objectItem[str]){
temporaryArr.push(objectItem)
}
})
//在数组循环结束后,将临时数组push进二维数组中
_arr.push(temporaryArr)
})
return _arr
},
incident() {
console.log(this.sortArr(this.obj, "name"));
},
},
};