我目前有以下界面:
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: '...'
}
]
}
]
}
]
}
]
这样做的原因是,我试图以前端,主要组为年份,第二个月,日期以及各自日期下的每个项目的方式在前端显示数据。
我已经在后端进行了分组,但是,我更加确信,这需要在前端进行,以便进行过滤和数据处理,而无需返回服务器。
提前致谢。
在没有矩和lodash的纯Javascript中,您可以使用
然后,对数据和组数组进行迭代,并为每个级别添加一个用于计数,最后将对象推入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; }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句