karate - 在空手道的 JSON 响应中从数组中获取最大值
问题描述
我有以下 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
}
}
]
}
}
我想找出这 3 天中哪个日期的温度最高。
我目前正在做的方式感觉效率低下,因为我正在检查我的 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
有了这个,我得到了正确的结果,但是有人可以建议一个更好的方法吗?
解决方案
空手道的最佳实践是根本不使用 JS for 循环。它会产生更清晰、更易读的代码:
* 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"
}
]
推荐阅读
- amazon-web-services - dmlx XGBoost 作业在随后提交时卡在 Yarn 中,处于“接受”状态
- javascript - 通过弹出表单更新数据库时表单提交不起作用
- angular - Angular Async Validator FormControls 在模糊之前不会更新
- php - 使用 Mockery 在 Laravel 的存储库模式中模拟 find($collection)
- angular - Angular (7):材料、日期选择器、验证未正确验证(始终无效)
- jquery - jQuery UI 自动完成:如何让 TAB 选择列表中的第一个选项?
- google-cloud-platform - 使用 cli 在 GCP CloudShell 上部署 kubeflow:/home/user/.kube/config: no such file or directory
- sql - 获取具有最大员工数量的部门名称
- html - 为什么头要复制到身体上?
- mysql - 每月和组计数条目