获取值最接近数字X的JSON数据 [英] Get JSON data where value is nearest to number X
本文介绍了获取值最接近数字X的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用户输入的数字X.以及JSON格式的数据列表.
I have a user inputted number, X. Along with a list of data in JSON format.
**114** 80 145 175 240 320
**123** 85 155 190 260 345
**132** 90 170 205 280 370
我想在第一列中将X与最接近的数字匹配,然后在该行中返回以下值.
I would like to match X with the nearest number in the first column and then return the following values in that row.
不确定我是否已以最佳方式格式化JSON.但是,到目前为止,这是我所拥有的: http://jsfiddle.net/wuSux/
Not sure if I have formatted the JSON in the best way. But here is what I have so far: http://jsfiddle.net/wuSux/
推荐答案
尝试如下操作:
var data = [{"Body Weight":114," Untrained": 80," Novice": 145," Intermediate": 175," Advanced": 240," Elite": 320},
{"Body Weight":123," Untrained": 85," Novice": 155," Intermediate": 190," Advanced": 260," Elite": 345},
{"Body Weight":132," Untrained": 90," Novice": 170," Intermediate": 205," Advanced": 280," Elite": 370}];
var x = 140,
difference = 0,
bestIndex = 0,
bestDifference = Infinity,
i, cur, bodyWeight;
for (i = 0; i < data.length; i++) {
cur = data[i];
bodyWeight = cur["Body Weight"];
difference = Math.abs(x - bodyWeight);
if (difference < bestDifference) {
bestDifference = difference;
bestIndex = i;
}
}
console.log(data[bestIndex]);
演示: http://jsfiddle.net/wuSux/2/
更改x
的值以查找与该数字最接近的数字.
Change the value of x
to find the closest to that number.
这篇关于获取值最接近数字X的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文