0

Here is my JSON code. I'm storing this json in an array.

{
"kind": "urlshortener#url",
"id": "http://example.com/2FIrtF",
"longUrl": "http://hike.com/?utm_source=facebook",
"status": "OK",
"created": "2015-09-22T13:45:53.645+00:00",
"analytics": {
    "allTime": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "month": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "week": {
        "shortUrlClicks": "1",
        "longUrlClicks": "1",
        "referrers": [
            {
                "count": "1",
                "id": "unknown"
            }
        ],
        "countries": [
            {
                "count": "1",
                "id": "IN"
            }
        ],
        "browsers": [
            {
                "count": "1",
                "id": "Chrome"
            }
        ],
        "platforms": [
            {
                "count": "1",
                "id": "Macintosh"
            }
        ]
    },
    "day": {
        "shortUrlClicks": "0",
        "longUrlClicks": "0"
    },
    "twoHours": {
        "shortUrlClicks": "0",
        "longUrlClicks": "0"
    }
},
"result": {
    "kind": "urlshortener#url",
    "id": "https://www.hike.com/?utm_source=facebook-pp&utm_medium=anvy&utm_campaign=naveen-2&utm_term=%2F&utm_content=100",
    "longUrl": "http://hike.com/?utm_source=facebook",
    "status": "OK",
    "created": "2015-09-22T13:45:53.645+00:00",
    "analytics": {
        "allTime": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "month": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "week": {
            "shortUrlClicks": "1",
            "longUrlClicks": "1",
            "referrers": [
                {
                    "count": "1",
                    "id": "unknown"
                }
            ],
            "countries": [
                {
                    "count": "1",
                    "id": "IN"
                }
            ],
            "browsers": [
                {
                    "count": "1",
                    "id": "Chrome"
                }
            ],
            "platforms": [
                {
                    "count": "1",
                    "id": "Macintosh"
                }
            ]
        },
        "day": {
            "shortUrlClicks": "0",
            "longUrlClicks": "0"
        },
        "twoHours": {
            "shortUrlClicks": "0",
            "longUrlClicks": "0"
        }
    }
}

}

In the above JSON, how can we get the existence of analytics -> day -> countries?

I want to know whether the countries exists in day or not first, if it's not, show some value. If it is there, it will try to fetch the count of particualr country.

I'm trying this from last 5 hours without any luck.

if(arr.analytics.day.countries !== undefined) {
         function thingscount(arr, platf) {
           var x = arr.analytics.day.countries.map(function(el) {
           return (platf.indexOf(el.id) != -1) ? parseInt(el.count) : 0; });
           var count = 0;
           for (var i = 0; i < x.length; i++) count += x[i];
           return count; 
           }       
            
        var one = thingscount(arr, ["US"]); 
            
        }else{
           var one = 0;
          
        }

The above code is working fine if there is countries in day, but sometimes, in my JSON there will be no platforms part, in that case it's giving me

Uncaught TypeError: Cannot read property 'map' of undefined

I need a way to check if the platforms exist, if it's go for a count, if it's not give some other value to the variable.

UPDATE :

I'm using this below code to get the count of IN.

When it has IN key and value, it's giving me the result. But when it don't has the IN key, it's showing 'undefined count' error.

var month_inclicks = arr.analytics.month.countries.filter(function(el) { return el.id == "IN"; })[0].count;

How can we set a default value if the key we are looking for is not exists?

2
  • That isn't JSON. jsonlint.com Commented Sep 25, 2015 at 13:53
  • Sorry, valid JSON updated. Commented Sep 25, 2015 at 14:02

3 Answers 3

3

While that isn't JSON, I'm assuming it's a javascript object. That being said, you'll want to look into utilizing the hasOwnProperty method or the in keyword.

Example:

if (arr.total.limited.hasOwnProperty('platforms')) { //do stuff

or

if ('platforms' in arr.total.limited) { //do something
Sign up to request clarification or add additional context in comments.

4 Comments

Just corrected the json. Can you please check the issue one more time?
Still invalid, see jsonlint.com . That said, it doesn't really change my answer. If you've already got it marshalled to a javascript object, you can simply utilize hasOwnProperty or in.
I'm using this below code to get the count of IN. When it has IN key and value, it's giving me the result. But when it don't has the IN key, it's showing 'undefined count' error. var month_inclicks = arr.analytics.month.countries.filter(function(el) { return el.id == "IN"; })[0].count; How can we set a default value if the key we are looking for is not exists?
Please post these kinds of updates in your question, not as a comment chain. Obviously a bit hard to read in this format.
2

I have corrected your JSON. use hasOwnProperty as @CollinD suggested

var arr = {
    total: {
        limited: {
            things: "451",
            platforms: [{
                count: "358",
                id: "Windows"
            }, {
                count: "44",
                id: "X11"
            }, {
                count: "42",
                id: "Macintosh"
            }, {
                count: "2",
                id: "Linux"
            }, {
                count: "1",
                id: "iPhone"
            }, {
                count: "1",
                id: "iPod"
            }]

        }
    }
};

Object.prototype.hasOwnProperty()

console.log(arr.total.limited.hasOwnProperty('platforms'));

DEMO

Comments

0

For the record, you can roll the map and the count in your 'thingscount' function into one operation by using reduce:

var getCount = function getCount( ary, find ) {
    return ary.reduce(function ( acc, record) {
        if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
        return acc;
    }, 0);
};

Usage inline:

if (arr.analytics.day.hasOwnProperty('countries')) {
    var find = ['IN'],
        count = arr.analytics.day.countries.reduce(function ( acc, record) {
            if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
            return acc;
        }, 0);
}

Or with the function:

if (arr.analytics.day.hasOwnProperty('countries')) {
    var count = getCount(arr.analytics.day.countries, ['US','IN']);
}

6 Comments

If you use an empty array as the input, no indexOf will be found and the default acc(umulator) value of 0 is returned. Like getCount(arr.analytics.day.countries, []); should return 0.
change the piece if (find.indexOf(record.id) !== -1) into if (find.indexOf(record.id) !== -1 && record.hasOwnProperty('count')) If you then have a country that has an id, but no count, it won't throw an error. The 0 comes from the reduce itsself, since we pass in 0 as the startvalue of 'acc'. All the countries that are in the 'find' array and that have a count value, will be added to the 0 we passed in. If the find array is empty, or if no countries in the array have a count, the 0 we passed in never gets a number added to it, so the result stays 0.
When i tried using function, it's giving me Uncaught TypeError: Cannot read property 'reduce' of undefined error. I put the first function and used as you shown in the 3rd example. When i used 2nd code, it's giving me undefined output.
Then you probably tried using it on a non-existing array. If you'll use the 2nd code, update it with the check if it has the property 'country'. Or just use your original way of counting. Good luck.
2nd code is working fine. But i need to use it multiple times in the page so looking for a function to work :) What might be the issue with the function?
|

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.