如果某个键在数组中重复,我想组合该键的值。例如,我有以下数组。
var arrays = [
["Product":"Item0", "Price":"15"],
["Product":"Item1", "Price":"53"],
["Product":"Item2", "Price":"12"],
["Product":"Item1", "Price":"83"],
["Product":"Item0", "Price":"10"],
["Product":"Item3", "Price":"88"],
["Product":"Item0", "Price":"44"]
]
我想像这样改变这个数组。
[
["Product": "item0", "Price": "69"],
["Product": "item1", "Price": "136"],
["Product": "item2", "Price": "12"],
["Product": "item3", "Price": "88"]
]
我该怎么办?
这是我写的代码。但是,如果复制了两个以上的键,则不会显示确切的值。你可以在这里解决一下,或者给我一个新的方法吗?
var arrays= [
["Product":"Item0", "Price":"15"],
["Product":"Item1", "Price":"53"],
["Product":"Item2", "Price":"12"],
["Product":"Item1", "Price":"83"],
["Product":"Item0", "Price":"10"],
["Product":"Item3", "Price":"88"],
["Product":"Item0", "Price":"44"]
]
var filteredArrays = [[String:String]]()
var sum : Int = 0
for i in 0..<arrayOfDicts.count {
let Product1 = arrayOfDicts[i]["Product"]
if(i == 0){
filteredArrays.append(arrayOfDicts[i])
} else {
var flag = false
for j in 0..<filteredArrays.count {
let Product2:String = filteredArrays[j]["Product"]!
if Product1 == Product2 {
sum += (Int(arrayOfDicts[i]["Price"]!)! + Int(arrayOfDicts[j]["Price"]!)!)
filteredArrays[j] = ["Product":"\(arrayOfDicts[i]["Product"]!)", "Price":"\(sum)"]
sum = 0
flag = true
}
}
if !flag {
filteredArrays.append(arrayOfDicts[i])
}
}
}
谢谢
答案 0 :(得分:1)
将字典转换为数组
var result = [String : Int]()
for product in arrays {
if let productKey = product["Product"] {
let value = Int(product["Price"] ?? "0")
if result[productKey] == nil, let value = value {
result[productKey] = value
} else if let value = value {
result[productKey]! += value
}
}
}
let newArray = result.map {["Product":$0, "Price": $1]}
答案 1 :(得分:0)
只是为了好玩,而不是胆小的人,使用Swift 4新方法let result = arrays.reduce(into: [String : Int]()) {
$0[$1["Product"] ?? "", default: 0] += Int($1["Price"] ?? "") ?? 0 }
.map { ["Product": $0, "Price": $1] }
和基于字典键的下标默认值:
print(result)
module.exports = [{
method: 'GET',
path: '/api/users',
handler: User.list,
config: {
responseCode: 200
}
}, {
method: 'POST',
path: '/api/users',
handler: User.create,
config: {
responseCode: 201
}
}]
“[[”Product“:”Item0“,”Price“:69],[”Product“:”Item2“,”Price“: 12],[“产品”:“第1项”,“价格”:136],[“产品”:“第3项”,“价格”: 88]] \ n“个