循环遍历多个数组并保持每个元素的计数

我的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" }] }] 

所以,从本质上讲,我希望能够遍历所有post的产品处理类型,并将它们与产品处理类型列表进行比较,并且只要有匹配,我想跟踪特定的次数。类型已匹配/使用/找到。

我目前正在以这种方式检查匹配,但我不确定如何保持每种产品类型的计数:

 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; } } }) 

我试图将这个问题写成文字时遇到了一些麻烦,所以如果我需要澄清一些问题,请告诉我。

您可以像这样使用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)