我有一系列这样的词典:
"subtitles": [{
"index": 0,
"language": "eng",
"name": ""
}, {
"index": 1,
"language": "eng",
"name": ""
}, {
"index": 2,
"language": "rus",
"name": ""
}, {
"index": 3,
"language": "chi",
"name": ""
}, {
"index": 4,
"language": "est",
"name": ""
}, {
"index": 5,
"language": "hin",
"name": ""
}, {
"index": 6,
"language": "ind",
"name": ""
}, {
"index": 7,
"language": "kor",
"name": ""
}, {
"index": 8,
"language": "lav",
"name": ""
}, {
"index": 9,
"language": "lit",
"name": ""
}, {
"index": 10,
"language": "msa",
"name": ""
}, {
"index": 11,
"language": "chi",
"name": ""
}, {
"index": 12,
"language": "pol",
"name": ""
}, {
"index": 13,
"language": "tam",
"name": ""
}, {
"index": 14,
"language": "tel",
"name": ""
}, {
"index": 15,
"language": "tha",
"name": ""
}, {
"index": 16,
"language": "ukr",
"name": ""
}, {
"index": 17,
"language": "vie",
"name": ""
}]
我只想要语言密钥的唯一性。在上面的数组中,前两个元素有语言" eng",但我只希望第一个或第二个元素包含在过滤后的数组中。
答案 0 :(得分:1)
尝试这个解决方案。希望对您有所帮助。
let subtitleArray:[[String:Any]] = inputDictionary["subtitles"] as! [[String:Any]]
var languageArray = [String]()
var filteredSubtitleArray = subtitleArray.filter { (dict) -> Bool in
guard let lang = dict["language"] as? String,languageArray.contains(lang) == false else {
return false
}
languageArray.append(lang)
return true
}
答案 1 :(得分:0)
您可以减少阵列忽略重复的语言:
let reducedSubtitles = dict["subtitles"]!.reduce([[String: Any]]()) { (result, current) in
if result.contains(where: { $0["language"] as? String == current["language"] as? String }) {
return result
}
return result + [current]
}