1

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

asked Dec 27, 2013 at 22:05
3
  • Do you have an example of the JSON you get back? Commented Dec 27, 2013 at 22:08
  • 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. Commented Dec 27, 2013 at 22:08
  • { "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 }, Commented Dec 27, 2013 at 22:10

2 Answers 2

2

instead of:

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

try :

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

answered Dec 27, 2013 at 22:18
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Dec 27, 2013 at 22:22

1 Comment

Thank you for helping me understand. I really appreciate you taking the time to answer my question accurately.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.