Search code examples
javascriptarrayslodash

Count object property inside array using lodash or vanilla javascript


I have this object with nested arrays/objects:

{
"USA": [
    {
        "location": "New York",
        "municipality": "Manhattan",
    },
    {
        "location": "Texas",
        "municipality": "Austin",
    }
  ],
"CANADA": [
    {
        "location": "Ontario",
        "municipality": "no municipality",
    }
  ]
}

I want to use lodash or plain javascript to count how many location are inside the USA and CANADA. How is that possible?

desired result:

USA: 2
CANADA: 1

Solution

  • Just use the array lengths:

    var USA = myObj.USA.length;
    var Canada = myObj.CANADA.length;
    

    Or, for larger data sets:

    var result = {};
    Object.keys(myObj)
        .forEach(function(key,index) {
            result[key] = myObj[key].length;
        });