根据共享值合并两个字典数组

时间:2017-10-04 17:41:24

标签: swift

假设我有两个词典数组:

[["id":"1","color":"orange"],["id":"2","color":"red"]]

[["id":"1","fruit":"pumpkin"],["id":"2","fruit":"strawberry"]]

如何根据“id”合并这些内容,以便我得到

[["id":"1","color":"orange","fruit":"pumpkin"],["id":"2","color":"red","fruit":"strawberry"]]

我们知道两个数组的长度相同。我们不知道这两个数组是否在同一个顺序中。

在Swift中合并每个字典的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

Xcode 9中的Swift标准库引入了merge

该代码使用相同的array2过滤相应的id词典,并将键和值合并到array1中:

var array1 = [["id":"1","color":"orange"], ["id":"2","color":"red"]]
var array2 = [["id":"1","fruit":"pumpkin"], ["id":"2","fruit":"strawberry"]]

for (index, item) in array1.enumerated() {
    if let filtered = array2.first(where: {$0["id"]! == item["id"]! }) {
        array1[index].merge(filtered) { (current, _) in current }
    }
}

print(array1)

我不知道Swift 3.2中是否还有merge

答案 1 :(得分:0)

对于这个答案,我将假设第一个Array是可变的:

var xs = [["id": "1", "color": "orange"], ["id": "2", "color": "red"]]
let ys = [["id": "1", "fruit": "pumpkin"], ["id": "2", "fruit": "strawberry"]]

for x in xs.enumerated() {
  for y in ys {
    if x.element["id"] == y["id"] {
      for (key, value) in y {
        if x.element[key] == nil {
          xs[x.offset][key] = value
        }
      }
    }
  }
}

答案 2 :(得分:0)

Swift 4的新词典初始化程序将让你做一些非常令人印象深刻的魔术,包括合并这样:

let a1 = [["id":"1","color":"orange"],["id":"2","color":"red"]]
let a2 = [["id":"1","fruit":"pumpkin"],["id":"2","fruit":"strawberry"]]

let merged = Dictionary((a1+a2).map{($0["id"]!,Array($0))}){$0 + $1}
             .map{Dictionary($1 as [(String,String)]){$1}}

print(merged)
// [["id": "2", "fruit": "strawberry", "color": "red"], ["id": "1", "fruit": "pumpkin", "color": "orange"]]