let arr = [
{id:"1",name:'项目A',zh:'001',lz:'0001'},
{id:"1",name:'项目A',zh:'002',lz:'0001'},
{id:"1",name:'项目A',zh:'003',lz:'0001'},
{id:"2",name:'项目B',zh:'001',lz:'0001'},
{id:"2",name:'项目B',zh:'002',lz:'0002'},
{id:"2",name:'项目B',zh:'002',lz:'0003'},
{id:"2",name:'项目B',zh:'002',lz:'0004'},
{id:"3",name:'项目C',zh:'003',lz:'0001'},
{id:"3",name:'项目C',zh:'003',lz:'0002'},
{id:"3",name:'项目C',zh:'004',lz:'0001'},
{id:"4",name:'项目D',zh:'001',lz:'0001'},
]
// 1. 现根据id,对不同进行项目分组
const result = arr.reduce((acc, cur) => {
const index = acc.findIndex(item => item[0].id === cur.id);
if (index === -1) {
acc.push([cur]);
} else {
acc[index].push(cur);
}
return acc;
}, []);
console.log(result);
// 2.再根据不同的 'zh' 计算不同的元素,有多少不同楼幢
let num = 0
if(result.length>0){
// for (let i = 0; i < result.length; i++) {
// const obj = {} // 中间值 转换数据
// num += result[i].reduce((pre,cur)=>{
// obj[cur['zh']] ? '' : (obj[cur['zh']] = true && pre.push(cur));
// return pre
// },[]).length
// }
result.forEach(item=>{
const obj = {} // 中间值 转换数据
num += item.reduce((pre,cur)=>{
obj[cur['zh']] ? '' : (obj[cur['zh']] = true && pre.push(cur));
return pre
},[]).length
})
}
console.log(num);
JavaScript 对象数组筛选不同元素
最新推荐文章于 2024-08-14 15:45:18 发布