javascript - 从大列表中提取数据
问题描述
我有一个如下列表:
var list = [
{
id:1,
name: 'bss',
type_a: 1,
},
{
id:2,
name: 'bss',
type_a: 1,
},
{
id:3,
name: 'bss',
type_a: 2,
},
{
id:4,
name: 'bss',
type_a: 2,
},
{
id:6,
name: 'bss',
type_a: 2,
},
{
id:8,
name: 'bss',
type_a: 5,
},
{
id:9,
name: 'bss',
type_a: 8,
},
...
]
你看到列表,列表中的项目有一个type_a
参数:
我想提取type_a
出来,并将相同的 type_a 聚合成这样:
{
8: [ // the 8 is `type_a`
{
id:9,
name: 'bss',
type_a: 8,
},
],
},
5: [
{
id:8,
name: 'bss',
type_a: 5,
},
]
...
}
是否有更高效的功能来实现这一点?
我可以使用两个 for 循环来实现这一点,第一个是收集 type_a 类型,另一个用于列表,如果等于type_a
项目。
解决方案
您可以Array.reduce()
用于该输出:
var list = [
{
id:1,
name: 'bss',
type_a: 1,
},
{
id:2,
name: 'bss',
type_a: 1,
},
{
id:3,
name: 'bss',
type_a: 2,
},
{
id:4,
name: 'bss',
type_a: 2,
},
{
id:6,
name: 'bss',
type_a: 2,
},
{
id:8,
name: 'bss',
type_a: 5,
},
{
id:9,
name: 'bss',
type_a: 8,
}
];
var res = list.reduce((acc, item)=>{
if(acc[item.type_a]){
acc[item.type_a].push(item);
return acc;
}
acc[item.type_a] = [];
acc[item.type_a].push(item);
return acc;
}, {});
console.log(res);
推荐阅读
- python - 通过@staticmethod 或@classmethod 访问属性和方法之间有什么实际区别吗?
- sql - SQL Redshift:如何在基于另一列值的连接中使用值
- python - peewee - 动态更改架构
- git - 解决与 VS2019 + KDiff3 的冲突时,Git 标记开始出现
- qt - QTableWidget:行大小不正确
- qt - 如何在 yocto 配方中添加 qt5 应用程序?
- python - 将每个 sas 数据集转换为 pandas 中的数据框
- r - alias() 不返回任何内容,而 vif() 在 R 中返回 NAN
- java - 如何修复税率操作?
- javascript - javascript - 遍历 ViewBag 列表