遍历多个数组并保持每个元素的计数 [英] Loop through multiple array and keep count of each element
问题描述
我的JSON
看起来像这样:
[{
"Name": "Test Post",
"Id": 123,
"ProductHandlingTypes": [{
"Id": 1,
"Name": "Type 1"
},
{
"Id": 2,
"Name": "Type 2"
}]
},
{
"Name": "Test Post 2",
"Id": 124,
"ProductHandlingTypes": [{
"Id": 3,
"Name": "Type 3"
},
{
"Id": 1,
"Name": "Type 1"
}]
}]
因此,从本质上讲,我希望能够遍历所有帖子的产品处理类型,并将它们与产品处理类型列表进行比较,只要有匹配项,我就希望跟踪多少匹配/使用/找到特定类型的次数.
So, in essence, I would like to be able to loop through all of the post's product handling types and compare them to a list of product handling types and anytime there is a match, I would like to keep track of how many times that specific type has been matched/used/found.
我目前正在以这种方式检查匹配项,但是我不确定如何保持每种产品类型的合计:
I am currently checking for matches this way, but I'm unsure of how to keep a tally of each product type:
postDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/path/to/get/posts",
dataType: "json"
}
},
schema: {
parse: function (response) {
// Get all product handling types
viewModel.productHandlingTypesDataSource.fetch(function() {
var types = this.data();
// Loop through all of the posts
for (var i = 0; i < response.length; i++) {
// Loop through each product handling type for each post
for (var j = 0; j < response[i].ProductHandlingTypes.length; j++) {
// Loop through every product handling type
for (var k = 0; k < types.length; k++) {
// Check if product handling type matches the post's product handling type(s)
if (response[i].ProductHandlingTypes[j].Name == types[k].Name) {
// Keep track of how many times this name matches
}
}
}
}
})
return response;
}
}
})
尝试将这个问题写成文字时遇到了一些麻烦,因此,如果我需要澄清更多内容,请告诉我.
I've had some trouble trying to put this issue into words so if I need to clarify some more just let me know.
推荐答案
您可以像这样使用reduce
:
var a = [{"Name":"TestPost","Id":123,"ProductHandlingTypes":[{"Id":1,"Name":"Type1"},{"Id":2,"Name":"Type2"}]},{"Name":"TestPost2","Id":124,"ProductHandlingTypes":[{"Id":3,"Name":"Type3"},{"Id":1,"Name":"Type1"}]}];
var b = a.reduce((acc, cur) => {
cur.ProductHandlingTypes.map(({Name}) => Name).forEach(n => acc[n] = (acc[n] || 0) + 1);
return acc;
}, {})
console.log(b)
它遍历数组并递增Type n
值,或者在不存在的情况下创建它们.
It loops through your array and increments Type n
values or creates them is they don't exist.
这篇关于遍历多个数组并保持每个元素的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!