javascript - 如何根据属性对对象进行分组
问题描述
希望可以有人帮帮我,
情况: 我正在开发一个单元报告,我在其中选择所有带有 unit_id 的客户(unit_id 是与单元的关系,它们可以在哪里找到),这个选择是一个对象数组,我有如何根据一个特定属性对对象进行分组时遇到了麻烦,我有一个数组,例如:
const clients = [
[
{
ID: 1,
NAME: 'John Doe',
UNITS: ['02'],
}
],
[
{
ID: 2,
NAME: 'Jane Doe',
UNITS: ['01', '02'],
}
],
[
{
ID: 3,
NAME: 'Doe John',
UNITS: ['50', '15'],
}
],
[
{
ID: 4,
NAME: 'Doe Jane',
UNITS: ['30'],
}
],
[
{
ID: 5,
NAME: 'Doe Jane',
UNITS: ['15'],
}
],
]
问题:我需要用相同的“ UNIT ” 对每个人进行分组,但是我不能在一个组中拥有多个具有相同“ UNIT ID ”的组,我期待的结果如下:
const unitGroups = [
[
{
UNIT_IDS: ['01', '02'],
CLIENTS: [
{
ID: 1,
NAME: 'John Doe',
},
{
ID: 2,
NAME: 'Jane Doe',
}
]
}
],
[
{
UNIT_IDS: ['50', '15'],
CLIENTS: [
{
ID: 3,
NAME: 'Doe John',
},
{
ID: 5,
NAME: 'Doe Jane',
}
]
}
],
[
{
UNIT_IDS: ['30'],
CLIENTS: [
{
ID: 4,
NAME: 'Doe Jane',
}
]
}
]
]
解决方案
你可以利用reduce
以达到效果。这是一个实现:
const clients = [ [ { ID: 1, NAME: 'John Doe', UNITS: ['02'], } ], [ { ID: 2, NAME: 'Jane Doe', UNITS: ['01', '02'], } ], [ { ID: 3, NAME: 'Doe John', UNITS: ['50', '15'], } ], [ { ID: 4, NAME: 'Doe Jane', UNITS: ['30'], } ], [ { ID: 5, NAME: 'Doe Jane', UNITS: ['15'], } ]];
const result = clients.reduce((a,e)=>{
e.forEach(({UNITS, ...rest})=>{
const getIndex = a.findIndex(p=>p.UNIT_IDS.some(b=>UNITS.some(c=>c===b)));
if(getIndex===-1){
const newData = {UNIT_IDS:UNITS, CLIENTS:[].concat(rest)};
a.push(newData);
} else {
a[getIndex].UNIT_IDS = [...new Set([...a[getIndex].UNIT_IDS, ...UNITS])];
a[getIndex].CLIENTS = [...a[getIndex].CLIENTS, rest]
}
})
return a;
},[]);
console.log(result);
推荐阅读
- python - Python-Selenium:无法从 html/javascript 字符串中抓取图像
- xslt - XSLT 2.0 - 如何在输出文件中默认包含属性?
- laravel - 尝试在单个函数中使用更新和创建的问题
- html - LoginForm 在 Django 中产生未知的验证错误
- sql - 如何检查存储在 SQL Server DB 表中的 word 文件中某些字符串的可用性?
- python - 多个分隔符的嵌套列表中的文本到 CSV(跳过第一次出现)
- excel - 如何修复 Excel VBA 中的“下标超出范围”错误:在表的更改事件中获取目标单元格的行号
- php - 使用 Doctrine Query Builder 转换 SQL 查询
- linux - 按数字顺序对制表符分隔文件中的行进行排序
- django - 在 django 中执行 PostgreSql 查询