js数组如何分组?
[{ "departmentName": "检验室(Lab Test)",
"queueTotalNumber": 3,
"personnelList": [{
"departmentName": "检验室(Lab Test)",
"medicalPersonnelName": "张其",
"departmentId": "05",
"clinicNo": "检验室001",
"queueNo": "2007"
}, {
"departmentName": "检验室(Lab Test)",
"medicalPersonnelName": "张刘",
"departmentId": "05",
"queueNo": "2006"
}, {
"departmentName": "检验室(Lab Test)",
"medicalPersonnelName": "张捌",
"departmentId": "05",
"queueNo": "2008"
}, {
"departmentName": "检验室(Lab Test)",
"medicalPersonnelName": "李叁",
"departmentId": "05",
"queueNo": "2012"
}],
"departmentId": "05"
}, {
"departmentName": "五官科 (EENT)",
"queueTotalNumber": 0,
"personnelList": [],
"departmentId": "06"
}, {
"departmentName": "妇科",
"queueTotalNumber": 0,
"personnelList": [],
"departmentId": "08"
}, {
"departmentName": "妇科1",
"queueTotalNumber": 0,
"personnelList": [],
"departmentId": "08"
}, {
"departmentName": "妇科2",
"queueTotalNumber": 0,
"personnelList": [],
"departmentId": "08"
}]
如何把上面的第一层数据每2个分组,第二层数据personnelList 每2个分组
回答:
loadsh 的chunk方法,可以试试:https://www.lodashjs.com/docs...
_.chunk(arr.map(item => ({
...item,
personnelList: _.chunk(item.personnelList, 2)
})),
2)
回答:
这样应该就可以了,优化我就不帮你优化了。
data.reduce((pv, cv, i)=>{ // 计算组数量
pv[Math.floor(i / 2)] = pv[Math.floor(i / 2)] || []
pv[Math.floor(i / 2)].push(cv);
cv.personnelList2 = cv.personnelList.reduce((pv,cv,i)=>{
// 计算组数量 同上
pv[Math.floor(i / 2)] = pv[Math.floor(i / 2)] || []
pv[Math.floor(i / 2)].push(cv);
return pv;
},[])
return pv;
}, [])
回答:
function groupFixLength(list, len, cb) { return list.reduce((res, v) => {
const pre = res[res.length-1]
if(pre && pre.length < len) pre.push(v)
else res.push([v])
cb && cb(v)
return res
},[])
}
groupFixLength(data, 2, v => v.personnelList = groupFixLength(v.personnelList, 2))
回答:
const getResInterval2 = (data) => { const baseInterval2 = (arr) => {
const res = []
for (let i = 0; i < arr.length; i += 2) {
const t = arr[i + 1] ? [arr[i], arr[i + 1]] : [arr[i]]
res.push(t)
}
return res
}
for (let i = 0; i < data.length; i++) {
data[i].personnelList = baseInterval2(data[i].personnelList)
}
return baseInterval2(data)
}
以上是 js数组如何分组? 的全部内容, 来源链接: utcz.com/p/932831.html