【问题标题】:Loop through multiple array and keep count of each element循环遍历多个数组并保持每个元素的计数
【发布时间】:2017-10-22 16:28:08
【问题描述】:

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

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

我目前正在以这种方式检查匹配项,但我不确定如何记录每种产品类型:

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

我在试图用语言表达这个问题时遇到了一些麻烦,所以如果我需要进一步澄清,请告诉我。

【问题讨论】:

标签: javascript jquery kendo-ui


【解决方案1】:

你可以像这样使用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 值或创建它们(如果它们不存在)。

【讨论】:

  • 这正是我想要的。谢谢!
猜你喜欢
  • 2019-01-20
  • 2020-12-22
  • 2014-12-08
  • 1970-01-01
  • 2011-08-28
  • 2017-08-16
  • 2012-01-04
  • 1970-01-01
相关资源
最近更新 更多