简体   繁体   English

使用Javascript在JSON文件中查找最常用的值

[英]Find most used values in JSON file with Javascript

I have a JSON file set up as follows 我有一个JSON文件设置如下

"mediaPosts": [
  {
      "index": 0,
      "source": "Twitter",
      "post": "commodo cillum in ut aliquip ad commodo esse duis sunt pariatur nostrud quis quis magna non ipsum Lorem cupidatat laboris",
      "sentiment": "Positive",
      "date": "24/05/2014",
      "gender": "Male",
      "age": 30,
      "country": "Gabon"
  },....]

The file contains 4000 records. 该文件包含4000条记录。

What I would like to know is what would be the best way to find 5 countries that appear the most in this JSON file 我想知道的是找到这个JSON文件中出现次数最多的5个国家的最佳方法

The only way I can think to do this is the following: 我认为做到这一点的唯一方法是:

1.Create a variable for every country in the world (This would mean the creation of a wopping 196 variables) 1,为世界上每个国家创建一个变量(这意味着创建196个变量)

2.Loop through my JSON list 2.遍历我的JSON列表

for (i = 0; i < postObject.mediaPosts.length; i++)
  1. Check the country string value for each record and increase the count of the corresponding country variable 检查每个记录的国家/地区字符串值,并增加相应国家/地区变量的计数

    if (postObject.mediaPosts[i].country == "Afghanistan") {afghanistan++;} else if (postObject.mediaPosts[i].country == "Albania") {albania++;} if(postObject.mediaPosts [i] .country ==“阿富汗”){afghanistan ++;}否则if(postObject.mediaPosts [i] .country ==“ Albania”){albania ++;}

  2. Then find the 5 largest values amogst my country variables 然后在我的国家/地区变量中找到5个最大值

However this process feels very cumbersome so I was wondering if there is a better way to do this> 但是这个过程感觉很麻烦,所以我想知道是否有更好的方法可以做到这一点>

var countries = {};

for (i = 0; i < postObject.mediaPosts.length; i++) {
    var country = postObject.mediaPosts[i].country;
    countries[country] = countries[country] ? countries[country] + 1 : 1
}

then you will have an object (an associative array) of the countries as keys, and their count in the input object. 那么您将有一个国家的对象(关联数组)作为键,并且它们在输入对象中计数。 Something like this: 像这样:

countries = {
    "Afghanistan" : 5,
    "Albania" : 3,
    "Bulgaria" : 2,
    //... the other countries
}

From there you can loop over it and create pairs from it 从那里您可以遍历它并从中创建对

var countryCountPairs = {};

for (country in countries) {
    countryCountPairs.push({country : country,  count : countries[country]});
}

Which will get you a data structure like this: 这将为您提供如下数据结构:

countryCountPairs = {
    { country : "Afghanistan",  count : 5 },
    { country : "Albania",  count : 3 },
    { country : "Bulgaria",  count : 2 },
    //... the other countries
}

And that is easily sortable: 这很容易排序:

countryCountPairs.sort(function(a, b) {
    // I think biggest value comes first with this, but you will have to test it. 
    return b.count - a.count;  
});

Which will give you a sorted version of the above. 这将为您提供以上的排序版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM