使用javascript汇总来自json的数据

时间:2016-09-09 10:35:30

标签: javascript json

如何通过" order"显示活动?与外部.json和js

外部.json

[{
  "activity": "Shift Log",
  "lat": "53.3630",
  "lon": "-6.2432"
}, {
  "activity": "Shift Log",
  "lat": "53.3422",
  "lon": "-6.2617"
}, {
  "activity": "Clock In",
  "lat": "53.3431",
  "lon": "-6.2802"
}]

代码:

<!DOCTYPE html>
<html lang="en">
<head></head>
  <title>SUM ACTIVITY</title>
    <script type="text/javascript">
    function sum (activity) {
        var min=1;
        var max = 4 // max number off json 
        var markersArray = [];
        var random = Math.floor(Math.random()*max)+min;
        var jsonfile = "pointer" + random.toString()+".json" //

        $.getJSON(jsonfile, function(pointer) {
            console.log("Loaded points from file: " + jsonfile);

                $.each(pointer, function(index, ponto) {
                console.log("Read points: " + JSON.stringify(ponto[0].length));

            });
        });
    }

    </script>
</html>

应该显示活动的数量 Shift log = 2,Clock In = 1

2 个答案:

答案 0 :(得分:0)

只需使用Temp Array存储&#39; Shift日志&#39;和&#39;时钟输入&#39;

var shiftLogArr = [],
    clockInArray = [],
    shiflog = "Shift Log",
    clockin = "Clock In" ;

$.getJSON(jsonfile, function(pointer) {

  $.each(pointer, function(index, item) {
   if(item.activity === shiflog) {
    shiftLogArr.push(item);
   }

   if(item.activity === clockin) {
    clockInArray.push(item);
   } 

 });
});

它&#39;只是我的意见,希望这有帮助!

答案 1 :(得分:0)

使用UnderscoreJS,您可以使用_.countBy函数

轻松实现此目的
var jsonObj = [{
  "activity": "Shift Log",
  "lat": "53.3630",
  "lon": "-6.2432"
}, {
  "activity": "Shift Log",
  "lat": "53.3422",
  "lon": "-6.2617"
}, {
  "activity": "Clock In",
  "lat": "53.3431",
  "lon": "-6.2802"
}]

var countObjects = _.countBy(jsonObj, 'activity');

console.log(countObjects);

使用JSFiddle - https://jsfiddle.net/r7bfpdst/2/

希望这有帮助!