用空字符串替换字典数组中的 NSNull 值
Replace NSNull Values in Array of Dictionary with empty string
我有一个结构如下的数组,
[
{
"Id": 20,
"Name": "Name String",
"Email": null
},
]
我想用空字符串替换出现的 null。我试过下面的地图方法,但没有成功。
let tempResult = recordsList.map{ [=11=] is NSNull ? "" : [=11=] }
您的结构是字典数组。映射时,每个元素都是一个字典。使用该字典构建一个新字典,其中 NSNull
s 已被空字符串替换:
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:)
并映射字典以将空值更改为空字符串来实现:
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
}
我有一个结构如下的数组,
[
{
"Id": 20,
"Name": "Name String",
"Email": null
},
]
我想用空字符串替换出现的 null。我试过下面的地图方法,但没有成功。
let tempResult = recordsList.map{ [=11=] is NSNull ? "" : [=11=] }
您的结构是字典数组。映射时,每个元素都是一个字典。使用该字典构建一个新字典,其中 NSNull
s 已被空字符串替换:
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:)
并映射字典以将空值更改为空字符串来实现:
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
}