2024年07月24日 建站教程
let arr = [ {date: '2022-06-06', name:'张三', age: '18'}, {date: '2022-06-06', name:'李四', age: '25'}, {date: '2022-06-07', name:'王五', age: '34'}, {date: '2022-06-07', name:'张三', age: '18'}, {date: '2022-06-07', name:'小明', age: '38'}, {date: '2022-06-08', name:'王五', age: '34'}, {date: '2022-06-09', name:'小白', age: '24'} ]
//方法 let dataArr = []; arr.map(items => { if (dataArr.length == 0) { dataArr.push({ name: items.name, list: [items] }) } else { let res = dataArr.some(item=> {//判断相同名字,有就添加到当前项 if (item.name == items.name) { item.list.push(items) return true } }) if (!res) {//如果没找相同名字添加一个新对象 dataArr.push({ name: items.name, list: [items] }) } } })
console.log('输出结果', dataArr) //输出结果 //0: {name: '张三', List: Array(2)} //1: {name: '李四', List: Array(1)} //2: {name: '王五', List: Array(2)} //3: {name: '小明', List: Array(1)} //4: {name: '小白', List: Array(1)}
本文链接:http://so.lmcjl.com/news/9075/