Loop through multiple array and keep count of each element

只愿长相守 提交于 2020-01-30 11:00:50

问题


My JSON looks something like this:

[{
    "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.


回答1:


You can use reduce like this:

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)

It loops through your array and increments Type n values or creates them is they don't exist.



来源:https://stackoverflow.com/questions/44122604/loop-through-multiple-array-and-keep-count-of-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!