2

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
0

3 Answers 3

3

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;
    });
Sign up to request clarification or add additional context in comments.

2 Comments

i want to iterate, the array has ~400 objects
@StathisNtonas: Added an example for that.
3

With lodash you could use mapValues:

let result = _.mapValues(data, 'length');

Comments

2

The solution using Array.prototype.reduce() function:

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

    result = Object.keys(obj).reduce(function(r,k){
        r[k] = obj[k].length;
    	return r;
    }, {});

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.