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

huangapple go评论77阅读模式
英文:

How to group array based on same value

问题

我正在使用golang,这是使用结构创建的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"**对数据进行分组。

英文:

I am using golang this is json data those are created using struct. But we need to group data using rooms->code basis value.

In this below json data need to group array using Room Code wise. Not to create Duplicate json node.
Actual Json Data

{
"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": ""
}

Need to convert my actual output

{
"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": ""
}

Need to group data on "code": "8525"

答案1

得分: 1

你可以遍历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": ""
}
英文:

You can iterate over the rooms and store each unique room.code in a map. When you encounter a code you have seen before, just add it to the array of rates which will be your value for that key in the map. Then just work your way up plugging in the new numbers in to your existing data structure.

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": ""
}            

huangapple
  • 本文由 发表于 2021年10月8日 20:18:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/69495726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定