从空手道中的JSON响应中的数组中获取最大值

问题描述 投票:2回答:1

我有以下Json作为API调用的响应

{
  "location": {
    "name": "London",
    "region": "City of London, Greater London",
    "country": "United Kingdom",
    "lat": 51.52,
    "lon": -0.11,
    "tz_id": "Europe/London",
    "localtime_epoch": 1583594426,
    "localtime": "2020-03-07 15:20"
  },
  "forecast": {
    "forecastday": [
      {
        "date": "2020-03-03",
        "day": {
          "maxtemp_c": 9,
          "mintemp_c": 4
        }
      },
      {
        "date": "2020-03-04",
        "day": {
          "maxtemp_c": 8,
          "mintemp_c": 4.1
        }
      },
      {
        "date": "2020-03-05",
        "day": {
          "maxtemp_c": 7,
          "mintemp_c": 5.6
        }
      }
    ]
  }
}

我想找出三天当中哪个日期温度最高。

我正在检查js函数中的温度元素时,我目前的工作方式效率很低,如下所示

* def hottest = 
        """
        function(array) {
        var greatest;
        var indexOfGreatest;
        for (var i = 0; i < array.length; i++) {
        if (!greatest || array[i].day.maxtemp_c > greatest) {
           greatest = array[i].day.maxtemp_c;
           indexOfGreatest = i;
           }
        }
        return indexOfGreatest;
       }
  """
* def index = call hottest response.forecast.forecastday
* def hottestdate = response.forecast.forecastday[index].date
* print hottestdate 

有了这个,我得到了正确的结果,但是有人可以建议一种更好的方法吗?

karate
1个回答
2
投票

空手道的最佳做法是完全不使用JS循环。这样可以生成更清晰,更易读的代码:

* def fun = function(x){ return { max: x.day.maxtemp_c, date: x.date } }
* def list = karate.map(response.forecast.forecastday, fun)
* def max = 0
* def index = 0
* def finder =
"""
function(x, i) {
  var max = karate.get('max');
  if (x.max > max) {
    karate.set('max', x.max);
    karate.set('index', i);
  }  
}
"""
* karate.forEach(list, finder)
* print 'found at index', index
* print 'item:', list[index]

请注意,对给定的JSON进行重塑非常容易,这里list的结果将是:

[
  {
    "max": 9,
    "date": "2020-03-03"
  },
  {
    "max": 8,
    "date": "2020-03-04"
  },
  {
    "max": 7,
    "date": "2020-03-05"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.