需要计算JSON密钥的出现*值 [英] Need to count JSON key occurence * value

查看:76
本文介绍了需要计算JSON密钥的出现*值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我以这种格式返回JSON:

So, I have JSON being return in this format:

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

我需要计算在这里代表多少个C和多少个T.例如,上面有82个C(2 * 23 + 1 * 36)和60个T.然后将它们存储在新对象(或数组?)中,例如:

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,
}

请记住,涉及的字母是可变的,尽管总是只有两个,并且采用以下格式:AA,AB,BB.甚至可能更好,将key:value对放入数组中(因为它们将用于制作条形图).

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.)

推荐答案

jsFiddle示例: http://jsfiddle.net/2HEVT/

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

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;
}

这篇关于需要计算JSON密钥的出现*值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆