我有一个具有这样结构的数组,
[
{
"Id": 20,
"Name": "Name String",
"Email": null
},
]
我想用空字符串替换空出现。我尝试了下面的map方法,但是没有运气。
let tempResult = recordsList.map{ $0 is NSNull ? "" : $0 }
答案 0 :(得分:1)
您的结构是一个字典数组。映射时,每个元素将是一个字典。使用该字典来构建新的字典,其中NSNull
被空字符串替换:
let recordsList: [[String : Any]] = [
[
"Id": 20,
"Name": "Name String",
"Email": NSNull()
]
]
let result: [[String : Any]] = recordsList.map { dict in
var newdict = [String : Any]()
for (k, v) in dict {
newdict[k] = v is NSNull ? "" : v
}
return newdict
}
print(result)
[["Email": "", "Id": 20, "Name": "Name String"]]
这也可以通过使用Dictionary(uniqueKeysWithValues:)
并通过映射字典以将null更改为空字符串来实现:
let result: [[String : Any]] = recordsList.map { dict in
Dictionary(uniqueKeysWithValues: dict.map { (k, v) in (k, v is NSNull ? "" : v) })
}
您的问题被标记为NSDictionary
。可以通过一些更改来解决:
let result: [NSDictionary] = recordsList.map { dict in
Dictionary(uniqueKeysWithValues: (dict as! [AnyHashable : Any]).map { (k, v) in (k, v is NSNull ? "" : v) }) as NSDictionary
}