如何从字典数组中的所有具有相同名称的键中检索值

时间:2019-04-07 14:29:24

标签: arrays swift dictionary

我想从字典数组中所有字典的名为“ termKey”的键中检索值(因为我想在UITableView中显示值)。有什么建议吗?

这是字典数组:


const path = require("path");

// Export a function. Accept the base config as the only param.
module.exports = async ({ config, mode }) => {
  // `mode` has a value of 'DEVELOPMENT' or 'PRODUCTION'
  // You can change the configuration based on that.
  // 'PRODUCTION' is used when building the static version of storybook.

  // Make whatever fine-grained changes you need
  config.node = {
    __dirname: true,
    __filename: true
  };

  // Return the altered config
  return config;
};

这是扁平化的数组:

{
  "questionData": [
    {
      "termKey": "respiration"
    },
    {
      "termKey": "mammals"
    }
  ]
}

我想要的输出如下:[(key: "termKey", value: "respiration"), (key: "termKey", value: "mammals")]

3 个答案:

答案 0 :(得分:1)

let array = [(key: "termKey", value: "respiration"), (key: "termKey", value: "mammals")]
array.map({ $0.value })

您将获得一个类似于以下值的数组:

["respiration", "mammals"]

答案 1 :(得分:0)

在数组上使用compactMap并在闭包中查找字典键:

let questionData = [["termKey": "respiration"], ["termKey": "mammals"], ["badKey": "foo"]]

let values = questionData.compactMap { $0["termKey"] }
print(values)
["respiration", "mammals"]

compactMap对数组中的每个元素运行其闭包以创建新的数组。在这里,我们查找键"termKey"的值。字典查找返回一个可选值。如果密钥不存在,则结果为nilcompactMap跳过nil的值并解包存在的值。

答案 2 :(得分:0)

将JSON解码为结构,并将结果map转换为termKey的{​​{1}}值。

questionData

struct Response: Decodable {
    let questionData : [Question]
}

struct Question: Decodable {
    let termKey : String
}