Search code examples
jsonlodash

Find the number of occurrences of items in list inside a JSON


I've following JSON where I've ownerid with their car make. Is there a better way in lodash to get count by car makes from a predefined list.

Eg,

{
    "data": [
        {"ownerId":"00001", "make": "Honda"},
        {"ownerId":"00002", "make": "Nissan"},
        {"ownerId":"00003", "make": "Audi"},
        {"ownerId":"00004", "make": "Porsche"},
        {"ownerId":"00005", "make": "Honda"},
        {"ownerId":"00006", "make": "Honda"},
        {"ownerId":"00007", "make": "Audi"},
        {"ownerId":"00008", "make": "Volkswagen"},
        {"ownerId":"00009", "make": "Honda"},
        {"ownerId":"00010", "make": "Porsche"},
        {"ownerId":"00011", "make": "Volkswagen"}
    ]
}

Filter list for calculating count:

["Honda", "Audi", "Porsche"]

Expected result:

[{"Audi": 2}, {"Honda": 4}, {"Porsche": 2}]

There are other car makes in the input JSON but not considered since the filter list doesn't have it.


Solution

  • You can use _.countBy() to get and object of counts per make, and then _.pick() the items you want:

    const cars = {"data":[{"ownerId":"00001","make":"Honda"},{"ownerId":"00002","make":"Nissan"},{"ownerId":"00003","make":"Audi"},{"ownerId":"00004","make":"Porsche"},{"ownerId":"00005","make":"Honda"},{"ownerId":"00006","make":"Honda"},{"ownerId":"00007","make":"Audi"},{"ownerId":"00008","make":"Volkswagen"},{"ownerId":"00009","make":"Honda"},{"ownerId":"00010","make":"Porsche"},{"ownerId":"00011","make":"Volkswagen"}]};
    
    const list = ["Honda", "Audi", "Porsche"];
    
    const result = _.pick(_.countBy(cars.data, 'make'), list);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>