Austin Lovell
Austin Lovell

Reputation: 1049

Multidimensional Array Javascript

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']);.

Upvotes: 1

Views: 107

Answers (2)

Barmar
Barmar

Reputation: 780673

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.

Upvotes: 1

nzn
nzn

Reputation: 838

instead of:

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

try :

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

Upvotes: 2

Related Questions