gpt4 book ai didi

javascript - 如何为 SectionList 转换对象数组

转载 作者:行者123 更新时间:2023-11-30 20:33:55 27 4
gpt4 key购买 nike

我的 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但我还没有设法创建所需的结构

最佳答案

使用reducefind

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com