0

我对从一种形式的数组到另一种形式的数据结构转换表示怀疑。

我的输入数据的形式是,

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/,但它并不准确..

4

1 回答 1

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

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

演示

于 2012-08-03T06:22:39.940 回答