-
按将数组分组到字典
name
-
result
-
列举字典。如果列表中有多个项目
value
汇总数量,只追加一项
名称
和
whole_quantity
存在于所有记录和密钥的值中
全量
可以转换为
Int
let array = [["grocery_section": "other", "partial_quantity": "0", "name": "Ground turmeric", "unit": "teaspoons", "whole_quantity": "1"],
["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "1"],
["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "2"]]
let groupedDictionary = Dictionary(grouping: array, by: {$0["name"]!})
var result = [[String:String]]()
for (_, value) in groupedDictionary {
if value.isEmpty { continue }
else if value.count == 1 {
result.append(value[0])
} else {
let totalQuantity = value.map{Int($0["whole_quantity"]!)!}.reduce(0, +)
var mutableValue = value[0]
mutableValue["whole_quantity"] = String(totalQuantity)
result.append(mutableValue)
}
}