[英]Insert values into array of dictionary
我有一个字典数组,其中有两个字典,就像这样..
[
{
"sellingPrice" : "499",
"id" : "5",
"quantity" : "-2",
"transaction_id" : "",
"shipping_charges" : "",
"payment_method" : "",
"taxes" : "",
"applied_coupon_code" : "",
"discount_price" : "",
"transaction_type" : "",
"remaining_balance" : "",
"grand_total" : ""
},
{
"sellingPrice" : "500",
"id" : "8",
"quantity" : "79",
"transaction_id" : "",
"shipping_charges" : "",
"payment_method" : "",
"taxes" : "",
"applied_coupon_code" : "",
"discount_price" : "",
"transaction_type" : "",
"remaining_balance" : "",
"grand_total" : ""
}
]
在这里,仅前三个键具有值。 现在,如果我想在关键transaction_id
添加一个值“ COD”,该如何实现..?
另外请注意,数组中词典的数量并不总是2。它可以是任意数量。 因此,当我给密钥transaction_id
赋值“ COD”时,无论字典的数量是多少,都应该更新所有字典中的更改。
编辑直到现在我还是尝试过类似的方法。
dictionary["transaction_id"] = "CASH"
arrayOfDictionary.append(dictionary)
但是,这又添加了一个字典,其transaction_id
的值为“ CASH”,总共提供2个字典,而不是2个。
您可以遍历数组并更改每个字典的transaction_id
。
arrayOfDictionary.indices.forEach({ arrayOfDictionary[$0]["transaction_id"] = "COD" })
如果要进行多个更新,则只需在forEach
循环中执行此操作。 它将分别更改或添加值。
arrayOfDictionary.indices.forEach({
arrayOfDictionary[$0]["transaction_id"] = "COD"
arrayOfDictionary[$0]["anotherKey"] = "anotherValue"
})
另外,请注意,您有一个闭包数组而不是一个字典数组。 您必须将花括号{ }
更改为方括号[ ]
var arrayOfDictionary = [
[
"sellingPrice" : "499",
"id" : "5",
"quantity" : "-2",
"transaction_id" : "",
"shipping_charges" : "",
"payment_method" : "",
"taxes" : "",
"applied_coupon_code" : "",
"discount_price" : "",
"transaction_type" : "",
"remaining_balance" : "",
"grand_total" : ""
],
[
"sellingPrice" : "500",
"id" : "8",
"quantity" : "79",
"transaction_id" : "",
"shipping_charges" : "",
"payment_method" : "",
"taxes" : "",
"applied_coupon_code" : "",
"discount_price" : "",
"transaction_type" : "",
"remaining_balance" : "",
"grand_total" : ""
]
]
为了简化答案,我假设词典中只有一个键。
您可以通过映射当前数组来实现它,如下所示:
var myArray = [["transaction_id": ""], ["transaction_id": ""]]
myArray = myArray.map { (dict: [String: String]) -> [String: String] in
var copyDict = dict
copyDict["transaction_id"] = "COD"
return copyDict
}
print(myArray)
// [["transaction_id": "COD"], ["transaction_id": "COD"]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.