尝试创建一个函数,其第一个参数为字符串,第二个参数为 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/