字典数组:如果在单个字典中找到相同的值,则添加值Swift

时间:2018-12-22 05:13:18

标签: ios swift

我有一个这样的结构数组

[["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"]]

现在,我想从该部分中具有相同键值对的配料中找到相同的条目,如果找到,则希望将数量添加到一个中并制成一种配料。您可以检查上面的部分名称为“ OTHER”的数组,并在那里检查成分。我想将2个相同的成分合并为一个数量为1 + 1 = 2的成分。因此,最终结果应该像

[["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": "3"]]

我尝试过的是这里的循环,但我认为它不是有效的方法。那么,还有什么更好的方法可以解决这个问题?

My Code

    guard let first = ingredients.first else {
        return [] // Empty array
    }

    var uniqueIngredients: [[String:String]] = [first] // Keep first element

    for elem in ingredients.dropFirst() {
        let equality = ingredients.compactMap { $0["name"] == elem["name"] }.count
        if equality > 1 {
            // SAME NAME FOR 2 INGREDIENT FOUND
            // COMBINE BOTH OBJECT
        } else {
            // NEW NAME
            // ADD NEW OBJECT
        }
   }

1 个答案:

答案 0 :(得分:2)

  • 通过name将数组分组为字典
  • 创建变量result
  • 枚举字典。如果value中有不止一项,则将数量相加并仅追加一项

代码假定键namewhole_quantity存在于所有记录中,并且键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)
    }
}