Bwyss
Bwyss

Reputation: 1834

jquery count items in json

I have a JSON that looks like this:

({
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "properties": {
                "wkb_geometry": null,
                "code": "type 1",
                "code2": "type 3",
                "code3": "type 5",
                "updated_at": "2012-10-29T12:38:00.037Z"
            }, 
        },
        {
            "type": "Feature",
            "properties": {
                "wkb_geometry": null,
                "code": "type 1",
                "code2": "type 5",
                "code3": "type 7",
                "updated_at": "2012-10-29T12:38:00.037Z"
            },

        },
        {
            "type": "Feature",
            "properties": {
                "wkb_geometry": null,
                "code": "type 2",
                "code2": "type 3",
                "code3": "type 5",
                "activity_type": "children's play area",
                "updated_at": "2012-10-29T12:38:00.037Z"
            },

        }...

Basically I want to count all the codes in this Json i.e. there are 3 occurrences of type 5.

So far I have a loop that picks out all the type 1 codes, but I am not sure how to get the loop to count the items:

$.each(geojson.features, function(i, v) {
    if (v.properties.code.search(new RegExp(/type 1/i)) != -1) {
        console.log(v.properties.activity_type_code);
    }
});

Upvotes: 1

Views: 234

Answers (1)

Slippery Pete
Slippery Pete

Reputation: 3110

You just need to increment a counter inside the if statement:

var count = 0;
$.each(geojson.features, function (i, v) {
    if (v.properties.code.search(new RegExp(/type 1/i)) != -1) {
        count++;
    }
});
console.log(count);

Upvotes: 3

Related Questions