在Aurelia中创建分隔符
如果我有一个JSON数组,它看起来像在Aurelia中创建分隔符,aurelia,Aurelia,如果我有一个JSON数组,它看起来像 { "error":false, "events":[ { "id":1, "title":"First entry", "date":"2014-11-04" }, { "id":2, "title":"Second entry", "date":"2014-11-04" }, { "id":3, "title":"Third entry", "d
{
"error":false,
"events":[
{
"id":1,
"title":"First entry",
"date":"2014-11-04"
},
{
"id":2,
"title":"Second entry",
"date":"2014-11-04"
},
{
"id":3,
"title":"Third entry",
"date":"2014-11-05"
},
{
"id":4,
"title":"Fourth entry",
"date":"2014-11-06"
},
{
"id":5,
"title":"Fifth entry",
"date":"2014-11-06"
}
]
}
如何在repeat中创建日期分隔符,使DOM看起来像这样
2014-11-04第一个条目
第二项
2014-11-05
第三项
2014-11-06
第四项
第五个条目我只是将您的数据分组到一个数组中
@bindable events = [];
groupedEvents = [];
eventsChanged(newValue) {
let matchedGroup;
// clear the array
this.groupedEvents = this.groupedEvents.splice(0, this.groupedEvents.length)
newValue.forEach(event => {
let match = this.groupedEvents.filter(group => {
return group.name === event.date;
})[0];
if (!match) {
matchedGroup = { name: event.date, events: [] };
this.groupedEvents.push(matchedGroup);
}
matchedGroup.events.push(event);
});
}
在您看来,您可以迭代组-
<template repeat.for="group of groupedEvents">
<h1>${group.name}</h1>
<ul>
<li repeat.for="event of group.events">${title}</li>
</ul>
</template>
${group.name}
- ${title}
JavaScript分组大多是简单的旧ES6+代码,可能会更高效一些,但它应该给您一个开始。您只是想对数据进行分组吗?是,也不是。我希望对其进行分组,我已经使用排序函数完成了分组。但我还想显示它的分组依据。每个标题都应该让用户知道条目所在的组。Brilliant&Grate雅:)为什么要使用splice清除数组?(我有一些问题,我不确定我是否完全理解那里发生了什么)我还必须将“let matchedGroup”放在forEach循环之外,否则,每个事件都会被清除,事件不会添加到matchedGroup数组中。我认为如果可以帮助的话,您不想重新分配数组的值,这样就不会破坏任何观察者。您是对的,匹配的组需要在循环之外定义(我从未实际测试过代码:)