根据值处理JSON对象/数组

时间:2018-10-23 09:58:26

标签: javascript json loops ecmascript-6

尝试创建一个函数,该函数的第一个参数为字符串,第二个参数为JSON LIST:

[
    {
        "date": "09/09/18",
        "how_many": 11,
        "species": "XXXXX"
    },
    {
        "date": "04/11/17",
        "how_many": 41,
        "species": "TTTTTT"
    },
    {
        "date": "17/03/18",
        "how_many": 30,
        "species": "DDDDDDDD"
    },
    {
        "date": "17/08/18",
        "how_many": 31,
        "species": "XXXXX"
    },
]

如果该字符串出现在每个JSON条目的“种类”计数中,则它将返回出现的次数。

本质上是一个函数,该函数返回其“ species”键与该函数的第一个参数匹配的对象数组(或列表)中出现的次数吗?

2 个答案:

答案 0 :(得分:1)

您可以使用Array.reduce

从文档中,

  

reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。

     

您的reducer函数的返回值分配给累加器,该值在整个数组的每次迭代中都被记住,并最终成为最终的单个结果值。

EXPLANATION

您现在知道,reduce函数会将数组简化为单个值,这里是所有匹配的种类的总和。 sum的默认值为0。进行迭代时,我们根据传递的物种值检查对象的物种。如果该值匹配,则将其 how_many 值添加到总和中。

ES6

let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];

function findOccurences(str, arr) {
  return arr.reduce((a,c) => a + (c.species === str ? c.how_many : 0), 0);
}

console.log(findOccurences("XXXXX", list));

ES5

let list = [{"date":"09/09/18","how_many":11,"species":"XXXXX"},{"date":"04/11/17","how_many":41,"species":"TTTTTT"},{"date":"17/03/18","how_many":30,"species":"DDDDDDDD"},{"date":"17/08/18","how_many":31,"species":"XXXXX"}];

function findOccurences(str, arr) {
  // Here a - accumulator and c - current value
  return arr.reduce(function(a, c){
    // If the species of object is same as passed value (str), add it to total sum
    if(c.species === str) {
      a += c.how_many;
    }
    return a;
  }, 0);
}

console.log(findOccurences("XXXXX", list));

答案 1 :(得分:0)

尝试一下:

function getCount(str, jsonArr) {
   var match = jsonArr.filter(obj=> obj.species === str);
   return match.length;
}