javascript - 根据id对数组数据进行分组

标签 javascript reactjs redux redux-reducers

通过 API 调用,我收到如下响应

[
  {
    stationId: "10"
    name: "Jinbaolai"
    group: {id: "18", stationGroupName: "Ali"}
  },
  {
    stationId: "13"
    name: "Stack"
    group: {id: "18", stationGroupName: "Ali"}
  },
  {
    stationId: "20"
    name: "Overflow"
    group: {id: "19", stationGroupName: "Baba"}
  }

]

正如您所看到的,前两条记录属于同一组。我想根据组对这些数据进行分组。例如,它应该看起来像这样

[
  {
    groupId: "18",
    groupName : "Ali",
    stations : [
                 {
                  stationId: "10",
                  name: "Jinbaolai"
                 },
                 {
                  stationId: "13",
                  name: "Stack"
                 }
               ]

  },
  {
    groupId: "19",
    groupName : "Baba",
    stations : [
                 {
                  stationId: "20",
                  name: "Overflow"
                 },
               ]

  }

]

我想在我的 reducer 中执行分组逻辑,其中我还设置了问题开头所示的完整数据数组。

            case EVC_SUCCESS:
            return {
                ...state,
                chargingStations: action.evcData.chargingStations,
                chargingStationGroups: //This is where my logic should go. ('action.evcData.chargingStations' is the initial data array)
                tableLoading: false
            }

我该怎么做?我尝试使用 filter 但没有成功。

最佳答案

最好的方法是使用 Array.prototype.reduce()

Reduce 是一个聚合函数,您可以在其中放入一些内容的数组并返回单个值。

可能有一个起始值作为最后一个参数,就像我使用的{}一样。 签名是 reduce(fn,startingValue),其中 fn 是一个带有两个参数 aggregatecurrentValue 的函数,其中您可以最后返回聚合。

const groupData = (data)=> {

    return Object.values(data.reduce((group,n)=>{
    if (!group[n.group.id]){
        group[n.group.id] = {
      groupId:n.group.id,
      groupName: n.group.stationGroupName,
      stations:[]}
    } 
    group[n.group.id].stations.push({
      stationID: n.stationId,
      name: n.name
    })
    return group;
  }, {}))

}

这是fiddle

关于javascript - 根据id对数组数据进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59434422/

相关文章:

javascript - 在 jQuery 中检索 click() 处理程序供以后使用

javascript - 了解事件循环

reactjs - 在 React 中显示逗号分隔的数组元素

javascript - 从异步操作中 react redux 显示数据

javascript - 获取 POST 输入错误的意外结束

redux - 使用 redux-saga 修改后端响应的最佳位置在哪里?

javascript - 将参数传递给 Vuex 中的 getter

javascript - jQuery:如何将鼠标悬停事件放在由ajax生成的标签选择上

javascript - Meteor 中长度为 0 的非空数组

javascript - 重置状态导致 React mixin 出现问题