组合JSON数据并使用下划线转换为数组

时间:2014-08-10 22:06:31

标签: javascript underscore.js

我有以下JSON数据:

    {
    "scan_stats": {
        "med_compl_clin": [
            {
                "clin": "Miller RPH, Susan S",
                "pct": "98"
            },
            {
                "clin": "Rollins RN, Beth L",
                "pct": "67"
            },
            {
                "clin": "Jenkins, Coney RUTH",
                "pct": "85"
            },
            {
                "clin": "Moore RPH, Kenneth W",
                "pct": "33"
            },
            {
                "clin": "Isaacs RPH, Daniel",
                "pct": "100"
            }
        ],
        "pt_compl_clin": [
            {
                "clin": "Miller RPH, Susan S",
                "pct": "34"
            },
            {
                "clin": "Rollins RN, Beth L",
                "pct": "88"
            },
            {
                "clin": "Wright , James ANTHONY",
                "pct": "90"
            },
            {
                "clin": "Jenkins, Coney RUTH",
                "pct": "75"
            },
            {
                "clin": "Moore RPH, Kenneth W",
                "pct": "58"
            }
        ]
    }
}

我试图找出如何将上述对象更改为一个阵列,该阵列具有阵列中每个临床(临床医生)的所有pct(百分比)。我希望不在med_compl_clin和pt_compl_clin对象中的临床医生在特定临床医生不会出现的对象的数组位置中为空:

[
  ["Miller RPH, Susan S", 98, 34],
  ["Rollins RN, Beth L", 67, 88],
  ["Wright , James ANTHONY", null, 90]
]  ... to the end of all clinicians

我正在尝试使用underscore.js来做到这一点,但无法做到正确。

1 个答案:

答案 0 :(得分:1)

仅使用javascript。

将json存储在变量

var json = {
    "scan_stats": {
        "med_compl_clin": [...],
        "pt_compl_clin": [...]
    }
}

然后尝试这段代码:

var newObject = {};
for( people in json.scan_stats.med_compl_clin ){
    newObject[ json.scan_stats.med_compl_clin[people].clin] = { med_ptc : json.scan_stats.med_compl_clin[people].pct };
}
for( people in json.scan_stats.pt_compl_clin ){
    if( !newObject[ json.scan_stats.pt_compl_clin[people].clin ] )
        newObject[json.scan_stats.pt_compl_clin[people].clin] = {};

    newObject[json.scan_stats.pt_compl_clin[people].clin].pt_ptc = json.scan_stats.pt_compl_clin[people].pct;
}

var json = [];
for( people in newObject ){
    var med = null;
    var pt = null;

    if( newObject[people].med_ptc ) med = parseInt(newObject[people].med_ptc);
    if( newObject[people].pt_ptc ) pt = parseInt(newObject[people].pt_ptc);

    json.push( [ people, med, pt ] );
}

现在变量“json”保存你的2d数组。