首页 > 解决方案 > 如何转换 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,但我没有设法创建所需的结构

标签: javascriptreact-native

解决方案


使用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)


推荐阅读