如何计算JSON数据在Jquery中具有具有特定值的键的次数?

时间:2018-08-06 01:23:59

标签: javascript jquery json

我的问题涉及以下JSON数据:

ad.find

谁能告诉我如何获取country = USA的次数?

在当前情况下,所需的输出为:2。

我一直在寻找解决方法,但是却找不到解决方法。

预先感谢您的帮助。

此致

5 个答案:

答案 0 :(得分:1)

循环遍历并计数。您可以为此使用reduce(),并在该值与所需值匹配时增加计数。

let o = {"matches":[{"country":"USA", "postcode":"9011"},{"country":"USA", "postcode":"9010"},{"country":"UK", "postcode":"BB3"}]}

let num_usa = o.matches.reduce((count, el) => {
  if (el.country === 'USA') count++
  return count
}, 0)
console.log(num_usa)

答案 1 :(得分:0)

我感谢回答用户提供的帮助。

由于某种原因,当我将JSON写入变量中时(可以在答复中使用),但是当ajax进程返回相同的JSON时,我无法处理。

通过切换到XML,终于解决了我的问题。

<matches>
    <result country = "USA" postcode = "9011" />
    <result country = "USA" postcode = "9011" />
    <result country = "UK" postcode = "BB3" />
</matches>

var countcountry = $(xml_result).find('result [country =“ usa”]')。length;

返回次数:2

答案 2 :(得分:0)

使用reduce绝对是我的建议。如果您想计算其他国家/地区,可以通过以下方式进行操作:

const response = {
  "matches": [{
    "country": "USA",
    "postcode": "9011"
  }, {
    "country": "USA",
    "postcode": "9010"
  }, {
    "country": "UK",
    "postcode": "BB3"
  }]
}

const countryCount = response.matches.reduce((acc, match) => {
  const country = match.country;
  if (!acc[country]) {
    acc[country] = 1;
  } else {
    acc[country]++;
  }
  return acc;
}, {});

// print USA and UK
console.log(countryCount.USA);
console.log(countryCount.UK);

答案 3 :(得分:0)

尝试一下:

var jsonObj = {"matches":[
  {
    "country":"USA", 
    "postcode":"9011"
  },
  {
    "country":"USA", 
    "postcode":"9010"
  },
  {
    "country":"UK", 
    "postcode":"BB3"
  }
]};

var count = 0;

for (var i in jsonObj.matches) {
   (jsonObj.matches[i].country == 'USA') ? count = count+1 : 0;  
}

console.log("Country count with USA :", count);

答案 4 :(得分:-1)

在这种情况下,使用Array#filter()和结果的长度非常简单

let data = {"matches":[{"country":"USA", "postcode":"9011"},{"country":"USA", "postcode":"9010"},{"country":"UK", "postcode":"BB3"}]}

let us_count = data.matches.filter(({country:c}) => c === 'USA').length

console.log(us_count)