javascript - 根据值处理 JSON 对象/数组

标签 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”键与函数的第一个参数匹配的对象数组(或列表)中出现的次数?

最佳答案

您可以使用Array.reduce

来自文档,

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array and ultimately becomes the final, single resulting value.

说明

正如您现在所知,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));

关于javascript - 根据值处理 JSON 对象/数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52946221/

相关文章:

javascript - 图片显示在除 Safari 和 Chrome 之外的所有浏览器中

javascript - 如何使用 react js 组件在网页上流式传输网络摄像头?

java - 使用 Mule ESB 解析 MySQL 存储过程结果集

python - 如何根据条件将数据框中的一列分割为多个系列

javascript - 为什么或为什么不为某些数据类型的核心函数提供简写?

Javascript事件和递归问题

javascript - JSON Schema 提取所需字段

json - 在 postgresql 更新触发器上测试数据类型

javascript - 通过 For 循环选择和添加函数到 Div

Excel宏: loop and append