作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 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 documentation我需要将我的原始数组结构从 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)
关于javascript - 如何为 SectionList 转换对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036723/
我是一名优秀的程序员,十分优秀!