【问题标题】:how to check if a particular json key has a value which is same for all the keys如何检查特定的 json 键是否具有与所有键相同的值
【发布时间】:2017-06-23 08:51:44
【问题描述】:
For example, I have a json response of array type where the second key in each array has same value. The count of the array is dynamic  but I need to check everytime, if that particular key value is same in all the arrays, i need to hide a label.

"loadable": [
      {
        "position": {
          "positionType": "XXX",
          "thirdKey": 1,
          "fourthKey": 1,
        },
      },
      {
          "position": {
          "positionType": "XXX",
          "thirdKey": 1,
          "fourthKey": 1,
        },
      },
      {
          "position": {
          "positionType": "XXX",
          "thirdKey": 1,
          "fourthKey": 1,
        },
{
        "position": {
          "positionType": "XXX",
          "thirdKey": 1,
          "fourthKey": 1,
        },
}
}
]

这里我想检查关键 positionType == "XXX" 的所有值,然后我需要隐藏一个标签。请迅速给出答案。

【问题讨论】:

  • "请尽快给出答案。"到目前为止,您尝试过什么?
  • for loadables { if loadable.position?.positionType == "XXX" { footer.labelTitle.isHidden = true }
  • 现在得到 4 个数组,其中所有值都是 XXX。但是我尝试的代码设置为true,即使有一个XXX和XXX以外的任何其他值
  • loadables 是 Loadable 类的 var,它是 NSManagedObject。 var loadables: [Loadable] = [] @
  • @vinny 然后显示 Loadable 的声明

标签: ios arrays json swift swift3


【解决方案1】:

如果要检查数组中的每个值是否相等,则可以这样。

let searchValue = "xxx"
if loadables.index(where: {$0.position?.positionType != searchValue}) != nil {
    //positionType for all objects are not equal to searchValue
    footer.labelTitle.isHidden = false
}
else {
    //positionType for all objects are equal to searchValue
    footer.labelTitle.isHidden = true
}

【讨论】:

  • 如果任何键与“XXX”匹配,这将起作用。但是如果所有键值都等于“XXX”,我想隐藏标签。如果至少一个值不是 XXX,我想显示标签
  • @vinny 然后这个解决方案非常适合这种情况还检查我是否编辑过答案尝试编辑过的答案
  • 非常感谢.. 解决了这个问题 :) @nirav D
  • @vinny 欢迎朋友 :)
【解决方案2】:

这不是一个 json 问题,而是一个“我的字典中的所有元素是否具有相同的值”的问题,其中元素将是您要查找的关键。

func checkValues(array: Array<Element>) -> Bool {

guard let myValue = array.firstObject()?.position?.positionType else {
    return false
}

for element in array {
    if element.position.positionType != myValue {
        return false
    }
}

return true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2021-12-10
    • 2022-01-15
    • 2013-01-04
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多