首页 > 解决方案 > 使用 lodash 基于时刻时间戳执行嵌套分组

问题描述

我目前有以下界面:

export interface IFoo {
    id: any;
    notes?: string;
    timestamp: any;
}

我正在使用的 API 当前返回此接口的数组,例如:

[{
    "id": 47,
    "notes": "asdas",
    "timestamp": "03/15/2020 08:47:42"
}, {
    "id": 48,
    "notes": "asdasd",
    "timestamp": "03/15/2020 15:16:12"
}]

将上面的结构转换为下面的结构有多可行?知道我正在使用 Observable 加载数据,所以我需要使用 rxjs:

this.foo$ = this.fooService.load
        .pipe(...

基本上在使用map或任何其他可能的运算符之后,响应应分为如下:(年、月、日)

[
    {
        year: YYYY,
        count: 0, // <- total `foos` in year
        months: [
            {
                month: 'January',
                count: 0, // <- total `foos` in month
                days: [
                    {
                        day: 0,
                        count: 0, // <- total `foos` in day
                        foos: [
                            {
                                Id: 0,
                                Notes: '...',
                                Timestamp: '...'
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

这样做的原因是我试图以主要组是一年,第二个月,一天和各自日期下的每个项目的方式在前端显示数据。

我已经在后端完成了分组,但是,我更相信这需要在前端完成,以进行过滤和数据操作,而无需返回服务器。

提前致谢。

标签: javascriptangulartypescript

解决方案


在没有momentlodash的纯 Javascript中,您可以为嵌套的 groupsm 获取一个数组

  • 钥匙,
  • 获取密钥的回调,
  • children 属性,用于下一个嵌套级别。

然后迭代数据和组数组,并为每个级别添加一个用于计数,最后将对象推送到foos.

var data = [{ id: 47, notes: "asdas", timestamp: "2020-03-15 08:47:42" }, { id: 48, notes: "asdasd", timestamp: "2020-03-15 15:16:12" }],
    groups = [
        ['year', ({ timestamp }) => timestamp.slice(0, 4), 'month'],
        ['month', ({ timestamp }) => timestamp.slice(5, 7), 'days'],
        ['days', ({ timestamp }) => timestamp.slice(8, 10), 'foos']
    ],
    result = data.reduce((r, o) => {
        groups
            .reduce((parent, [key, fn, children]) => {
                var group = parent.find(q => q[key] === fn(o));
                if (!group) parent.push(group = { [key]: fn(o), count: 0, [children]: [] });
                group.count++;
                return group[children];
            }, r)
            .push(o);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读