代码之家  ›  专栏  ›  技术社区  ›  user8411642

将值插入字典数组

  •  0
  • user8411642  · 技术社区  · 8 年前

    我有一个字典数组,其中有两个字典,如下所示。。

    [
    {
        "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个键有值。现在,如果我想给键添加一个值“COD” transaction_id 我如何实现它。。?

    另外请注意,数组中的字典数并不总是2。它可以是任何数字。所以当我给键赋值“COD”时 事务处理id 无论字典的数量是多少,所有字典中的更改都应该更新。

    到现在为止,我一直在尝试这样的东西。。

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

    但这又增加了一本字典,其值为 事务处理id 作为“现金”,总共提供2本词典,而不是2本。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Yannick    8 年前

    您可以迭代数组并更改 transaction_id 对于每个dict。

    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" : ""
    
        ]
    ]
    
        2
  •  0
  •   Ahmad F    8 年前

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

    你可以通过 映射 您当前的阵列,如下所示:

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