如何检查特定的json密钥是否具有对所有密钥相同的值

时间:2017-06-23 08:51:45

标签: ios arrays json swift swift3

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,
        },
}
}
]

这里我想检查关键位置= =“XXX”的所有值,然后我需要隐藏标签。请快速提供答案。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:0)

这不是一个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
}