从空手道中的JSON响应中的数组中获取最大值 [英] Getting the maximum value from an array in a JSON response in Karate

查看:44
本文介绍了从空手道中的JSON响应中的数组中获取最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following Json as a response from a API call

{
  "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
        }
      }
    ]
  }
}

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

I want to find out which date had the highest temperature amongst the 3 days.

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

The way I am currently doing feels inefficient as I am checking for the temperature element within my js function and it is as follows

* 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 

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

With this I am getting the correct result but can someone kindly suggest a better way of doing this?

推荐答案

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

Best practice in Karate is to NOT use JS for loops at all. It results in cleaner, more readable code:

* 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的结果将是:

Note how easy it is to re-shape a given JSON, the result of list here would be:

[
  {
    "max": 9,
    "date": "2020-03-03"
  },
  {
    "max": 8,
    "date": "2020-03-04"
  },
  {
    "max": 7,
    "date": "2020-03-05"
  }
]

这篇关于从空手道中的JSON响应中的数组中获取最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆