我有这样的JSON响应:
[
{
"category": C5,
"group": G43
},
{
"category": C5,
"group": G43
},
{
"category": C10,
"group": G1
},
{
"category": C10,
"group": G1
},
{
"category": C3,
"group": G1
},
{
"category": C3,
"group": G1
},
{
"category": C2,
"group": G3
},
{
"category": C4,
"group": G3
}
]
我需要将“类别”和“组”分组,其中它们的值相等。我想创建键为“ category”且值是2组数组的字典。结果必须是这样的:
[
C5 : [G43]
C10 : [G1]
C3 : [G1, G2]
C2 : [G3]
C4 : [G3]
]
我创建了两个不同的类,一个用于类别,一个用于组,我尝试使用for循环来实现,并且尝试在{循环中使用Dictionary(grouping:, by:)
,但是我认为我没有错路径。我需要将数组分组两次吗?我如何以一种干净的方式来做?
答案 0 :(得分:2)
与其尝试使用字典,不如尝试将它们转换为实际上代表数据的类型……
struct Something {
let category: String
let group: String
}
let array = [Something(category: "C5", group: "G43"),
Something(category: "C5", group: "G43"),
Something(category: "C10", group: "G1"),
Something(category: "C10", group: "G1"),
Something(category: "C3", group: "G1"),
Something(category: "C3", group: "G2"),
Something(category: "C2", group: "G3"),
Something(category: "C4", group: "G3")]
let groups = Dictionary(grouping: array, by: {$0.category} )
group.forEach { key, somethings in
print(key)
print(somethings.map({$0.group}))
}
C10
["G1", "G1"]
C3
["G1", "G2"]
C5
["G43", "G43"]
C2
["G3"]
C4
["G3"]
编辑
如果您要删除重复的组…
group.forEach { key, somethings in
print(key)
print(Set(somethings.map({$0.group})))
}
C3
["G1", "G2"]
C2
["G3"]
C4
["G3"]
C5
["G43"]
C10
["G1"]
,如果您真的想要使用词典,并失去结构附带的类型安全性和自动完成功能……
let array = [["category": "C5", "group": "G43"],
["category": "C5", "group": "G43"],
["category": "C10", "group": "G1"],
["category": "C10", "group": "G1"],
["category": "C3", "group": "G1"],
["category": "C3", "group": "G2"],
["category": "C2", "group": "G3"],
["category": "C4", "group": "G3"]]
let group = Dictionary(grouping: array, by: {$0["category"]} )
group.map { key, somethings in
print(key!)
print(Set(somethings.map({$0["group"]!})))
}