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

时间:2017-05-22 21:44:49

标签: javascript jquery kendo-ui

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

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

1 个答案:

答案 0 :(得分:3)

您可以像这样使用Type n

&#13;
&#13;
{{1}}
&#13;
&#13;
&#13;

它循环遍历您的数组并增加{{1}}值或创建它们是否不存在。