版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1、首先一级与二级相同的嵌套
let arr = [ { date: '2020-01-06', age: '18'}, { date: '2020-01-06', age: '25'}, { date: '2020-01-07', age: '34'}, { date: '2020-01-07', age: '18'}, { date: '2020-01-07', age: '38'}, { date: '2020-01-08', age: '26'}, { date: '2020-01-09', age: '24'} ]
let dataArr = []; arr.map(mapItem => { if (dataArr.length == 0) { dataArr.push({ date: mapItem.date, List: [mapItem] }) } else { let res = dataArr.some(item=> {//判断相同日期,有就添加到当前项 if (item.date == mapItem.date) { item.List.push(mapItem) return true } }) if (!res) {//如果没找相同日期添加一个新对象 dataArr.push({ date: mapItem.date, List: [mapItem] }) } } })
结果
dataArr = [ { date:'2020-01-06', List: [ { date: '2020-01-06', age: '18'}, { date: '2020-01-06', age: '25'} ] }, { date:'2020-01-07', List: [ { date: '2020-01-07', age: '34'}, { date: '2020-01-07', age: '18'}, { date: '2020-01-07', age: '38'}, ] }, { date:'2020-01-08', List: [ { date: '2020-01-08', age: '26'}, ] }, { date:'2020-01-09', List: [ { date: '2020-01-09', age: '24' } ] } ]
第二种情况:一级四位数(0001),二级八位数字(00010001)获取的条件是通过一级的四位数字匹配二级的前四位数字
方法1:
var userArr = [ { id: "0001", userName: "laozhang_1" }, { id: "00010001", userName: "laozhang1" }, { id: "00010002", userName: "laozhang1" }, { id: "00010003", userName: "laozhang1" }, { id: "0002", userName: "laowang" }, { id: "00020002", userName: "laozhang2" }, { id: "00020003", userName: "laowang" }, { id: "00020004", userName: "laowang" }, { id: "00020005", userName: "laowang" }, { id: "00020006", userName: "laowang" } ];
let newArr = [] userArr.forEach(item => { if (item.id.length === 4) { newArr.push({ ...item, list: [] }); } }); newArr.forEach(item => { userArr.forEach(user => { if (item.id !== user.id && item.id == user.id.substring(0, 4)) { item.list.push(user); } }); }); console.log(newArr)
方法2:
var userArr = [ { id: "0001", userName: "laozhang_1" }, { id: "00010001", userName: "laozhang1" }, { id: "00010002", userName: "laozhang1" }, { id: "00010003", userName: "laozhang1" }, { id: "0002", userName: "laowang" }, { id: "00020002", userName: "laozhang2" }, { id: "00020003", userName: "laowang" }, { id: "00020004", userName: "laowang" }, { id: "00020005", userName: "laowang" }, { id: "00020006", userName: "laowang" } ];
let newArr = userArr.filter(item => item.id.length === 4) newArr.forEach(item => { item.list = userArr.filter(user => item.id !== user.id && item.id == user.id.substring(0, 4)) }) console.log(newArr)
总结:学好js基础很重要