我的API服务
有以下数组结构//In your service you make a variable "data"
data:any
fetchBuildingData(location) {
this.http.post(url, location, httpOptions).subscribe(resp => {
this.data=resp
});
}
//in yours components
get data()
{
return BuildingDataService.data
}
根据react-native documentation,我需要将原始数组结构从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
}
]
对于标题部分,我使用以下函数:toLocaleDateString
我想我可以使用数组方法reduce
,但我还没有设法创建所需的结构
答案 0 :(得分:1)
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)