将值插入字典数组中

时间:2017-11-09 09:19:51

标签: ios swift 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" : ""

  }
]

这里,前3个键只有值。现在,如果我想在键transaction_id中添加值“COD”,我该如何实现它?

另请注意,数组中的词典数量并不总是2.它可以是任何数字。因此,无论词典的数量是多少,我都会将值“COD”赋予键transaction_id,所有更改都应该更新。

编辑我到现在为止尝试过这样的事情..

dictionary["transaction_id"] = "CASH"
arrayOfDictionary.append(dictionary)

但是这又添加了一个字典,其值transaction_id为“CASH”,共有2个字典,而不是2个。

2 个答案:

答案 0 :(得分:1)

您可以迭代数组并更改每个字典的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" : ""

    ]
]

答案 1 :(得分:0)

为了简化答案,我假设词典中只有一个键。

您可以通过映射当前数组来实现它,如下所示:

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"]]