我已经进行过搜索,但似乎找不到任何人提出同样的问题,这让我感到惊讶。
基本上我试图绘制一个与此类似的对象数组:
"objKey": {
"date": "[timestamp]",
"name": "Object Name",
"description": "Object Description"
}
我想将它映射到渲染到页面时看起来如下所示:
Today:
Object One – Object Description
Object Two – Object Description
Object Three – Object Description
Tomorrow:
Object One – Object Description
Object Two – Object Description
Object Three – Object Description
等等...
所以通常我只是通过数组创建一个函数,并返回我想要显示的值,但我不知道从哪里开始寻找如何分组'按日期这些对象?
如果可能的话,我想避免将它们缩减为新的数组,因为它会变得非常混乱,任何想法?
谢谢!
答案 0 :(得分:0)
您可以尝试使用此方法进行分组
const data = {
"date": "wednesday 18 April 2018",
"name": "React",
"description": "lorem"
}
const result = '';
let grouping = Object.keys(data).reduce((cur,prev)=>{
if(prev === 'date'){
const date = new Date();
const dateObj = new Date(data[prev]);
const diff = dateObj.getTime() - date.getTime();
const diffdays = Math.ceil(diff / (1000 * 3600 * 24));
result = diffdays == 0 ? 'Today' : diffdays == 1 ? 'Tommorrow' : data[prev];
cur[result] = {}
}
cur[result][prev] = data[prev];
return cur
},{})
console.log(grouping)
let value = Object.keys(grouping[result]).map((key)=>{
return <li>{key + ' : '+ grouping[result][key]}</li>
})
demo link