将数据数组转换为SectionList组件的分组数据

Kyl*_*aus 2 javascript arrays lodash react-native

我坦率地承认 Javascript 不是我最擅长的语言,而 React Native 是非常新的,因此,可能有一种我没有看到的明显简单的方法来做到这一点。

我有一个 API,它以简单的结构呈现一些交易数据:

[
  {
    "id": 1,
    "title": "Apple Store",
    "date": "2021-09-10",
    "amount": "$100.00",
  },
  {
    "id": 41,
    "title": "Zulauf, Walter and Metz",
    "date": "2021-09-10",
    "amount": "$14.00",
  },
  {
    "id": 9,
    "title": "Aufderhar PLC",
    "date": "2021-09-09",
    "amount": "$78.00",
  },
  {
    "id": 10,
    "title": "Bayer and Sons",
    "date": "2021-09-07",
    "amount": "$67.00",
  }
]
Run Code Online (Sandbox Code Playgroud)

我想使用SectionList 组件来呈现此数据,并按日期划分各部分中的交易。我(可能是粗略的)解决这个问题的尝试是将这些数据转换为以下结构:

[
  {
    "date": "2021-09-10",
    "transactions": [
      {
        "id": 1,
        "title": "Apple Store",
        "date": "2021-09-10",
        "amount": "$100.00",
      },
      {
        "id": 41,
        "title": "Zulauf, Walter and Metz",
        "date": "2021-09-10",
        "amount": "$14.00",
      }
    ]
  },
  {
    "date": "2021-09-09",
    "transactions": [
      {
        "id": 9,
        "title": "Aufderhar PLC",
        "date": "2021-09-09",
        "amount": "$78.00",
      }
    ]
  },
  {
    "date": "2021-09-07",
    "transactions": [
      {
        "id": 10,
        "title": "Bayer and Sons",
        "date": "2021-09-07",
        "amount": "$67.00",
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

但老实说,我不知道如何转换这些数据(或者是否有更好的方法来解决这个问题)。我首先使用 Lodash 的 groupBy 函数,这看起来很有前途,但看起来 SectionList 不需要一个对象,它需要一个数组。

将 groupBy 的输出直接转换为数组会丢弃键,并且我得到了分组数据,但节标题没有明确的值。

同样,可能有一些非常简单的方法来解决这个问题,数据始终以平面数组的形式出现。我感谢任何人可以向我指出的任何指导、帮助或示例。

Isa*_*aac 5

const input = [
  {
    "id": 1,
    "title": "Apple Store",
    "date": "2021-09-10",
    "amount": "$100.00",
  },
  {
    "id": 41,
    "title": "Zulauf, Walter and Metz",
    "date": "2021-09-10",
    "amount": "$14.00",
  },
  {
    "id": 9,
    "title": "Aufderhar PLC",
    "date": "2021-09-09",
    "amount": "$78.00",
  },
  {
    "id": 10,
    "title": "Bayer and Sons",
    "date": "2021-09-07",
    "amount": "$67.00",
  }
]

const result = input.reduce((accum, current)=> {
  let dateGroup = accum.find(x => x.date === current.date);
  if(!dateGroup) {
    dateGroup = { date: current.date, transactions: [] }
    accum.push(dateGroup);
  }
  dateGroup.transactions.push(current);
  return accum;
}, []);

console.log(result)
Run Code Online (Sandbox Code Playgroud)

给定一个数组,每当您的结果期望具有相同数量的元素时,请使用map,但由于您的结果具有不同数量的元素,请reduce如上所示使用。这个想法是通过让reduce, 循环每个元素,看看是否可以找到该元素,并将当前元素推入列表中