Get key and indices of selected elements Swift

前端 未结 2 1936
失恋的感觉
失恋的感觉 2021-01-27 23:41

I have one dictionary that contains an Array of Dictionaries.

\"other\":(
    {
         \"grocery_section\" = other,
         name = test
    },
    {
                  


        
相关标签:
2条回答
  • 2021-01-27 23:50

    You can make use of flatMap and compactMap:

    let matches = list.flatMap { key, value in
        // go through all elements in the array and convert the matching dictionaries in (key, index) pairs
        value.enumerated().compactMap { index, dict in
            dict["name"] == "test" ? (key, index) : nil
        }
    }
    print(matches)
    

    Sample output:

    [("other", 0), ("c0f5d6c5-4366-d310c0c9942c", 1)]
    

    If you want to avoid repeated pairs for the same key, you can use map instead of compactMap:

    let matches = list.map { key, value in
        (key, value.enumerated().compactMap { index, dict in
            dict["name"] == "test" ? index : nil
        })
    }
    

    Sample output:

    [("other", [0]), ("c0f5d6c5-4366-d310c0c9942c", [1])]
    

    The inner compactMap will build an array made of on only the items that have the name matching, while the outer flatMap will flatten an otherwise bi-dimensional array.

    0 讨论(0)
  • 2021-01-28 00:07

    Enumerate the outer dictionary and get the indices with filter

    var filteredDict = [String:[Int]]()
    for (key, value) in dict {
        let indices = value.indices.filter{ value[$0]["name"] == "test" }
        if !indices.isEmpty { filteredDict[key] = indices }
    }
    

    The result is a [String:[Int]] dictionary, the keys are the dictionary keys, the values are the indices.
    With the given data the result is ["c0f5d6c5-4366-d310c0c9942c": [1], "other": [0]]

    If you want to update an item you have to specify the entire path due to value semantics

    list[key]![index]["propertyName"] = value
    
    0 讨论(0)
提交回复
热议问题