Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I can't seem to get anything to go into my ['count'] key. Any help would be appreciated.

<script>
        $.getJSON( "someAddress", function( data ) {
            $( ".result" ).html( data );
            var totalUse    =   new Array();
            var totalLen    =   data.stats.length;
            for(x = 0; x < totalLen; x++){
                var user    =   data.stats[x].userId;
                if(totalUse.indexOf(user) > -1){ // yes it does have it
                    totalUse[user]["count"] += data.stats[x].count;
                }else{
                    totalUse[user]          =   data.stats[x].userId;
                    totalUse[user]['count'] =   data.stats[x].count;
                    console.log(totalUse[user]['count']);
                }
            }
            console.log(totalUse[1]['count']);
        });
    </script>

This line is giving me grief: totalUse[user]['count'] = data.stats[x].count; I know that data.stats[x].count; contains data but it comes out as undefined when I do console.log(totalUse[user]['count']);.

share|improve this question
 
Do you have an example of the JSON you get back? –  jameslafferty 21 hours ago
1  
"I know that data.stats[x].count; contains data but it comes out as undefined." -- If the value is undefined, then what you "know" is wrong. Either count is undefined, stats does not have an index x, stats is null/undefined, or data is null/undefined. –  Brian S 21 hours ago
 
{ "stats":[ { "userId":13, "user":"AM Mobile", "service":"total", "month":"05/2013", "count":19694 }, { "userId":13, "user":"AM Mobile", "service":"total", "month":"06/2013", "count":4008 }, –  user1753797 21 hours ago
add comment

2 Answers

up vote 1 down vote accepted

Use this:

if (totalUse[user]){ // yes it does have it
    totalUse[user].count += data.stats[x].count;
}else{
    totalUse[user] = {
        userId: user,
        count: data.stats[x].count
    };
}

If you want to save both the userID and count in each element of totalUse, you have to put them in different properties of the object. You can't assign the userID directly to the array element.

share|improve this answer
 
Thank you for helping me understand. I really appreciate you taking the time to answer my question accurately. –  user1753797 21 hours ago
add comment

instead of:

totalUse[user]          =   data.stats[x].userId;
totalUse[user]['count'] =   data.stats[x].count;

try :

totalUse[user] = { count : data.stats[x].count };

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.