javascript - 如何转换 SectionList 的对象数组
问题描述
我的 API 服务有以下数组结构
[
{
id: 1001,
orderNo: 'abc',
customer: 'John',
date: 1524526218641
},
{
id: 1002,
orderNo: 'def',
customer: 'Ringo',
date: 1524555627191
},
{
id: 1003,
orderNo: 'ghi',
customer: 'George',
date: 1524555662611
},
{
id: 1004,
orderNo: 'jkl',
customer: 'Paul',
date: 1524717318641
}
]
根据react-native 文档,我需要将原始数组结构从 API 服务转换为:
[
{
title: '23/4/2018',
data: [
{
id: 1001,
orderNo: 'abc',
customer: 'John',
date: 1524526218641
}
]
},
{
title: '24/4/2018',
data: [
{
id: 1002,
orderNo: 'def',
customer: 'Ringo',
date: 1524555627191
},
{
id: 1003,
orderNo: 'ghi',
customer: 'George',
date: 1524555662611
}
]
},
{
title: '25/4/2018',
data: [
{
id: 1004,
orderNo: 'jkl',
customer: 'Paul',
date: 1524717318641
}
]
}
]
对于标题部分,我使用以下函数:toLocaleDateString
我想我可以使用数组方法reduce
,但我没有设法创建所需的结构
解决方案
const data = [
{
id: 1001,
orderNo: 'abc',
customer: 'John',
date: 1524526218641
},
{
id: 1002,
orderNo: 'def',
customer: 'Ringo',
date: 1524555627191
},
{
id: 1003,
orderNo: 'ghi',
customer: 'George',
date: 1524555662611
},
{
id: 1004,
orderNo: 'jkl',
customer: 'Paul',
date: 1524717318641
}
]
let res = data.reduce((re, o) => {
let existObj = re.find(
obj => obj.title === new Date(o.date).toLocaleDateString()
)
if (existObj) {
existObj.data.push(o)
} else {
re.push({
title: new Date(o.date).toLocaleDateString(),
data: [o]
})
}
return re
}, [])
console.log(res)
推荐阅读
- game-maker - 如何创建没有重复的随机物品生成器?
- java - 如何从 fat-jar 依赖项中排除依赖项
- javascript - 如何在 JavaScript/p5.js/HTML 中访问本地图像
- javascript - 如何防止对特定表列进行排序 - DataTable?
- c# - 无法在 ASP.NET 中将数据导出到 XML - 数据导出到 HTML 而不是 XML
- css - CSS未应用于表类
- c++ - 在 centOS7 上安装 ceres-solver 并让 helloworld.cc 工作
- arrays - 有没有办法在数组元素中使用 if 语句?
- python - 带日志的 Pandas NaN
- git - 为什么不忽略公共目录中的文件?