javascript 获取 JSON 文件中的前 10 个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27479750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:31:56  来源:igfitidea点击:

Getting top 10 Values in a JSON File

javascripthtmlarraysjsonparsing

提问by Gio Perez

This is an example of my JSON file.

这是我的 JSON 文件的示例。

[
    {"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
    {"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
    {"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
    {"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
    {"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
    {"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
    {"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
    {"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
    {"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
    {"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO  HALOO","Variable1":0}
]

How can I get only the Top 10 from highest Variable1 number to the least? But gonna be passing the JSON file as the same format.

我怎样才能从最高的 Variable1 数字到最少的前 10 名?但是将以相同的格式传递 JSON 文件。

回答by haim770

First, parse the JSON into an array of Objects:

首先,将 JSON 解析为对象数组:

var data = JSON.parse(json);

Then combine sortand sliceto achieve your goal:

然后结合sortslice实现您的目标:

var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
                .slice(0, 10);

See Array.sort

参见Array.sort

回答by agershun

You can do it with AlasqlJavaScript library. It download json file, parse it, and run SQL statement on it. This is a sample how to take top 10 directly from JSON file:

您可以使用AlasqlJavaScript 库来实现。它下载 json 文件,解析它,并在其上运行 SQL 语句。这是一个如何直接从 JSON 文件中获取前 10 名的示例:

<script src="alasql.min.js></script>
<script>
    alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){
        console.log(top10);
    });
</script>

Or if you already have data in memory:

或者,如果您的内存中已经有数据:

    var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
    var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);

Try this samplein jsFiddle.

在 jsFiddle 中试试这个示例