登录
首页 >  Golang >  Go问答

如何根据相同的值对数组进行分组

来源:stackoverflow

时间:2024-04-12 11:27:37 255浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《如何根据相同的值对数组进行分组》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在使用 golang,这是使用 struct 创建的 json 数据。但我们需要使用 rooms->code 基础值对数据进行分组。

在下面的 json 数据中,需要使用房间代码对数组进行分组。不要创建重复的 json 节点。 实际 json 数据

{
    "responsestatus": "success",
    "version": "v1.9",
    "checkin": "2021-10-12",
    "checkout": "2021-10-16",
    "currency": "aed",
    "hotels": [
        {
            "code": "ot000000001",
            "name": "taj test hotel",
            "rooms": [
                {
                    "code": "9011",
                    "name": "beach villa with jacuzzi",
                    "rates": [
                        {
                            "subsupplierid": "dc",
                            "boardcode": "fb",
                            "rateplancode": "9011_0_11_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 1469.04,
                            "cancellationpolicy": {
                                "policies": null
                            }
                        }
                    ]
                },
                {
                    "code": "8525",
                    "name": "doubello",
                    "rates": [
                        {
                            "subsupplierid": "dc",
                            "boardcode": "fb",
                            "rateplancode": "8525_0_11_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 4407.08,
                            "cancellationpolicy": {
                                "policies": null
                            }
                        }
                    ]
                },
                {
                    "code": "8525",
                    "name": "doubello",
                    "rates": [
                        {
                            "subsupplierid": "dc",
                            "boardcode": "",
                            "rateplancode": "8525_0_22_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 7345.12,
                            "cancellationpolicy": {
                                "policies": null
                            }
                        }
                    ]
                }
            ]
        }
    ],
    "remark": ""
}

需要转换我的实际输出

{
    "responseStatus": "SUCCESS",
    "version": "v1.9",
    "checkIn": "2021-10-12",
    "checkOut": "2021-10-16",
    "currency": "AED",
    "hotels": [
        {
            "code": "OT000000001",
            "name": "TAJ TEST HOTEL",
            "rooms": [
                {
                    "code": "9011",
                    "name": "Beach Villa With Jacuzzi",
                    "rates": [
                        {
                            "subSupplierId": "DC",
                            "boardCode": "FB",
                            "ratePlanCode": "9011_0_11_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 1469.04,
                            "cancellationPolicy": {
                                "policies": null
                            }
                        }
                    ]
                },
                {
                    "code": "8525",
                    "name": "Doubello",
                    "rates": [
                        {
                            "subSupplierId": "DC",
                            "boardCode": "FB",
                            "ratePlanCode": "8525_0_11_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 4407.08,
                            "cancellationPolicy": {
                                "policies": null
                            }
                        }, {
                            "subSupplierId": "DC",
                            "boardCode": "",
                            "ratePlanCode": "8525_0_22_136_136",
                            "channel": 23,
                            "allotment": 100,
                            "price": 7345.12,
                            "cancellationPolicy": {
                                "policies": null
                            }
                        }
                    ]
                }
            ]
        }
    ],
    "remark": ""
}

需要对“code”:“8525”的数据进行分组


正确答案


您可以迭代 rooms 并将每个唯一的 room.code 存储在 map 中。当您遇到以前见过的 code 时,只需将其添加到 rates 数组中,这将是 map 中该键的值。然后,只需将新数字插入到现有数据结构中即可。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type Response struct {
    Status   string  `json:"responseStatus"`
    Version  string  `json:"version"`
    CheckIn  string  `json:"checkIn"`
    CheckOut string  `json:"checkOut"`
    Currency string  `json:"currency"`
    Hotels   []Hotel `json:"hotels"`
    Remark   string  `json:"remark"`
}

type Hotel struct {
    Code  string `json:"code"`
    Name  string `json:"name"`
    Rooms []Room `json:"rooms"`
}

type Room struct {
    Code  string `json:"code"`
    Name  string `json:"name"`
    Rates []Rate `json:"rates"`
}

type Rate struct {
    SupplierID   string  `json:"subSupplierId"`
    BoardCode    string  `json:"boardCode"`
    RateCode     string  `json:"ratePlanCode"`
    Channel      int     `json:"channel"`
    Allotment    int     `json:"allotment"`
    Price        float64 `json:"price"`
    CancelPolicy Policy  `json:"cancellationPolicy"`
}

type Policy struct {
    Policies string `json:"policies"`
}

func main() {
    byt, err := ioutil.ReadFile("foo.json")
    if err != nil {
        os.Exit(1)
    }

    resp := Response{}
    json.Unmarshal(byt, &resp)
    hotels := resp.Hotels
    newHotels := make([]Hotel, 0)
    for _, hotel := range hotels {
        newRooms := make(map[string]Room)
        for _, room := range hotel.Rooms {
            if val, ok := newRooms[room.Code]; ok {
                newRates := append(val.Rates, room.Rates...)
                val.Rates = newRates
                newRooms[room.Code] = val
            } else {
                newRooms[room.Code] = room
            }
        }
        finalRooms := make([]Room, 0)
        for _, v := range newRooms {
            finalRooms = append(finalRooms, v)
        }
        hotel.Rooms = finalRooms
        newHotels = append(newHotels, hotel)
    }

    resp.Hotels = newHotels
    respJSON, err := json.MarshalIndent(resp, "", "  ")
    if err != nil {
       os.Exit(1)
    }
    fmt.Printf(string(respJSON))
}

{
  "responseStatus": "SUCCESS",
  "version": "v1.9",
  "checkIn": "2021-10-12",
  "checkOut": "2021-10-16",
  "currency": "AED",
  "hotels": [
    {
      "code": "OT000000001",
      "name": "TAJ TEST HOTEL",
      "rooms": [
        {
          "code": "9011",
          "name": "Beach Villa With Jacuzzi",
          "rates": [
            {
              "subSupplierId": "DC",
              "boardCode": "FB",
              "ratePlanCode": "9011_0_11_136_136",
              "channel": 23,
              "allotment": 100,
              "price": 1469.04,
              "cancellationPolicy": {
                "policies": ""
              }
            }
          ]
        },
        {
          "code": "8525",
          "name": "Doubello",
          "rates": [
            {
              "subSupplierId": "DC",
              "boardCode": "FB",
              "ratePlanCode": "8525_0_11_136_136",
              "channel": 23,
              "allotment": 100,
              "price": 4407.08,
              "cancellationPolicy": {
                "policies": ""
              }
            },
            {
              "subSupplierId": "DC",
              "boardCode": "",
              "ratePlanCode": "8525_0_22_136_136",
              "channel": 23,
              "allotment": 100,
              "price": 7345.12,
              "cancellationPolicy": {
                "policies": ""
              }
            }
          ]
        }
      ]
    }
  ],
  "remark": ""
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>