从一种阵列到另一种阵列的数据转换

时间:2012-08-03 05:51:47

标签: javascript jquery arrays

我怀疑从一种阵列到另一种阵列的数据结构转换。

我的输入数据格式为

var testVar=[

{
    "count": 1,
    "term": "Company",
    "Company": [
        {
            "Tata": [
                {
                    "count": 1,
                    "term": "Tatagroup"
                }
            ],
            "sector": "Automotive",
            "type": "Car"
        },
      ]
},
{
    "count": 2,
    "term": "Country",
    "Country": [
        {
            "France": [
                {
                    "count": 1,
                    "term": "France"
                }
            ],
            "region": "Europe",
            "Player": "Zidane",
            "term": "France",
            "code": "FRA"
        },
        {
            "region": "Europe",
            "Player": "Federer",
            "term": "Switzerland",
            "Switzerland": [
                {
                    "count": 1,
                    "term": "Switzerland"
                }
            ],
            "code": "SWI"
        }
    ]
}];

我试图将其转换为表格,

[ "Tata" : [{"sector" : "automotive"}, "type" : "car"], "France": [{"region" : "Europe}, {"Player" : "Zidane"} , {"code" : "FRA"}], "switzerland" : [{"region" : "Europe}, {"Player" : "Federer"} , {"code" : "SWI"}]];

我提出的代码看起来像http://jsfiddle.net/X2apw/2/,但它准确无误......

1 个答案:

答案 0 :(得分:2)

var testvar = [...];

var result = {};
for (var i=0; i<testvar.length; i++) {
    var arr = testvar[i][testvar[i].term];
    for (var j=0; j<arr.length; j++) {
        var resarr = [];
        for (var k in arr[j]) {
            if (typeof arr[j][k] == "string") {
                 var obj = {};
                 obj[k] = arr[j][k];
                 resarr.push(obj);
            } else {
                 result[k] = resarr;
            }
        }
    }
}

Demo at jsfiddle.net

但是,我强烈建议在结果格式中只使用一个对象而不是一个属性对象数组。将内循环体更改为:

        var resobj = {};
        for (var k in arr[j]) {
            if (typeof arr[j][k] == "string") {
                 resobj[k] = arr[j][k];
            } else {
                 result[k] = resobj;
            }
        }

Demo