Da Silva
Da Silva

Reputation: 229

data transformation from one form of array to another

I have doubt about data structure transformation from one form of array to another.

My input data is of the form,

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

and I am trying to transform it to the form,

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

The code I came up with looks like http://jsfiddle.net/X2apw/2/, bt its nt accurate..

Upvotes: 0

Views: 173

Answers (1)

Bergi
Bergi

Reputation: 664237

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)

However, I strongly recommend to use just one object instead of an array of one-property-objects in your result format. Change the inner loop body to:

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

(Demo)

Upvotes: 2

Related Questions