过滤具有特定属性 Swift 的 json 数组

Posted

技术标签:

【中文标题】过滤具有特定属性 Swift 的 json 数组【英文标题】:Filter array of json having certain property Swift 【发布时间】:2019-02-21 06:00:27 【问题描述】:

我只是 swift 的初学者。 我想过滤具有特定属性的 json 对象数组并从中创建新的 json 数组。

我的数组是:

[
  "marked" : 4,
  "attempted" : true,
  "correct" : 4,
  "subject" : 1,
  "status" : true,
  "question" : 550,
  "answer" : 34256,
  "time" : 23,
  "score" : 10,
  "chapter" : 26
, 
  "marked" : 1,
  "attempted" : true,
  "correct" : 1,
  "subject" : 1,
  "status" : true,
  "question" : 566,
  "answer" : 34317,
  "time" : 33,
  "score" : 14,
  "chapter" : 26
, 
  "marked" : 4,
  "attempted" : true,
  "correct" : 1,
  "subject" : 1,
  "status" : true,
  "question" : 590,
  "answer" : 34276,
  "time" : 33,
  "score" : 15,
  "chapter" : 26
]

我想要一个数组,其中 markedcorrect 具有相同的值。

我怎样才能快速做到这一点?

【问题讨论】:

【参考方案1】:

将其转换为带有对象的数组后,您可以简单地使用。

myArray.filter  $0.marked == $0.correct 

如果只是字典,你可以尝试按键查找它们的值

myArray.filter  $0["marked"]! == $0["correct"]! 

【讨论】:

以上是关于过滤具有特定属性 Swift 的 json 数组的主要内容,如果未能解决你的问题,请参考以下文章