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']);.
2 Answers 2
instead of:
totalUse[user] = data.stats[x].userId;
totalUse[user]['count'] = data.stats[x].count;
try :
totalUse[user] = { count : data.stats[x].count };
Comments
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.
1 Comment
Explore related questions
See similar questions with these tags.
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.