Graeck
Graeck

Reputation: 1356

Need to count JSON key occurence * value

So, I have JSON being return in this format:

{
   "CC" : 23,
   "CT" : 36,
   "TT" : 12,
}

I need to count how many C's and how many T's are represented here. For example, above there are 82 C's (2*23 + 1*36) and 60 T's. Then store these in a new object (or array?) like:

{
  "C" : 82,
  "T" : 60,
}

Keep in mind, the letters involved are variable, though will always only be two, and be in that format: AA,AB,BB. Or possible even better, putting the key:value pairs in an array (as these are to be used for making a bar chart).

(For the biologists, yes, counting allele frequencies from genotypes.)

Upvotes: 0

Views: 196

Answers (1)

haitaka
haitaka

Reputation: 1856

jsFiddle example: http://jsfiddle.net/2HEVT/

CODE:

function calc(o){
    var result={};
    for(var i=0;i<Object.keys(o).length;i++){
        str=Object.keys(o)[i];
        for(var j=0;j<str.length;j++){
            value=0;
            if(result.hasOwnProperty(str[j]))
                value=result[str[j]];
            result[str[j]]=value+o[str];
        }
    }
    return result;
}

Upvotes: 1

Related Questions