js 对数据进行分类
let data = [{
"functionType": "Channel",
"functionId": 94145
}, {
"functionType": "Channel",
"functionId": 94150
}, {
"functionType": "Channel",
"functionId": 94149
}, {
"functionType": "Channel",
"functionId": 94151
}, {
"functionType": "Channel",
"functionId": 94152
}, {
"functionType": "WebSite",
"functionId": 958
}]
forEach 方法
const groupedBy = {};
for (const item of items) {
if (groupedBy[item.type]) {
groupedBy[item.type].push(item);
} else {
groupedBy[item.type] = [item];
}
}
reduce 1.方法 ,方法不易理解
let arr = items.reduce(
(acc, item) => ({
...acc,
[item.type]: [...(acc[item.type] ?? []), item],
}),
{},
);
reduce 2. 方法 简单。和上面的for差不多
let arr = items.reduce(
(acc, item) => ({
...acc,
[item.type]: [...(acc[item.type] ?? []), item],
}),
{},
);
console.log(arr) //{
{
"Channel": [
{
"functionType": "Channel",
"functionId": 94145
},
{
"functionType": "Channel",
"functionId": 94150
},
{
"functionType": "Channel",
"functionId": 94149
},
{
"functionType": "Channel",
"functionId": 94151
},
{
"functionType": "Channel",
"functionId": 94152
}
],
"WebSite": [
{
"functionType": "WebSite",
"functionId": 958
}
]
}
filter 起来很容易阅读,但是性能很差,需要对数组进行多次过滤
const arr = {
WebSite: data .filter((item) => item.functionType === 'WebSite'),
Channel: data .filter((item) => item.functionType=== 'Channel'),
};
groupBy 简单方便。但还没上线
data.groupBy(({ functionType}) => functionType);
groupBy 的回调中一共有三个参数:
- 参数1:数组遍历到的当前对象
- 参数2:index 索引
- 参数3:原数组