0

In short, I have start my question,

I simply read json file,

 [{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Fixtures","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Vanities","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Concrete","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Fencing","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Gypsum","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulation","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulssdation","ThirdCategory":""}]

and trying to convert into array like

Array
(
  [Bath] => Array
    (
        [Bath Accessories] => Array
            (
                [0] => test
            )

        [Faucets] => Array
            (
                [0] => test1
                [1] => test2
            )

    )

)//sorry i have used PHP for simple formatting the array.

I spent lot of time on this stuff i can't get success please help me.

 My javascript code : (not working.)

 var FirstCategory = [];
 var SecondCategory = [];
 var ThirdCategory = [];


 $.getJSON('tree.json', function(data) {

var dataObj = new Array();
$.each(data,function(i){
    dataObj[data[i].FirstCategory] = new Array();

    if([data[i].SecondCategory] in dataObj[data[i].FirstCategory])
        dataObj[data[i].FirstCategory][data[i].SecondCategory] = data[i].SecondCategory;
    else
        dataObj[data[i].FirstCategory][data[i].SecondCategory] = new Array();

    dataObj[data[i].FirstCategory][data[i].SecondCategory][data[i].ThirdCategory] = new Array();

});

 console.log(dataObj);

/*
$.each(data,function(i){

    if (FirstCategory == '') {
        FirstCategory.push(data[i].FirstCategory);
    }
    else
    {
        if(!FirstCategory.contains(data[i].FirstCategory))
        {
            //root
            FirstCategory.push(data[i].FirstCategory);
        }
        else
        {
            //------- second level category -------//
            if (SecondCategory == '') {
                SecondCategory.push(data[i].SecondCategory);
            }
            else
            {
                if(!SecondCategory.contains(data[i].SecondCategory))
                {
                    SecondCategory.push(data[i].SecondCategory);
                }
                else
                {
                    ThirdCategory.push(data[i].ThirdCategory);
                }
            }

        }
    }   

});
*/

});


Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
        if (this[i] == obj) {
         return true;
      }
  }
   return false;
}

Thanks in advance.

3
  • 2
    Is there a reason your json is not already on that form? If not I would suggest changing the backend instead. Commented Nov 2, 2012 at 13:27
  • First thing you should do is realize that in JavaScript, what you're making is a plain object, and not an array. Commented Nov 2, 2012 at 13:29
  • Where did you get those test, test1, test2 values from? Commented Nov 2, 2012 at 13:43

3 Answers 3

2

Please notive that Javascript has no "associative arrays".

A bit more programmatically:

var levels = ["FirstCategory", "SecondCategory", "ThirdCategory"]; // possibly more
var dataObj = {}; // an empty object
for (var i=0; i<data.length; i++) {
    var cur = dataObj;
    for (var j=0; j<levels.length; j++) {
        var key = data[i][levels[j]];
        if (!key) // empty
            break;
        if (key in cur)
            cur = cur[key];
        else
            cur = cur[key] = {};
    }
}

result (dataObj) for your example input, formatted as JSON:

{
    "Bath": {
        "Bath Accessories": {},
        "Faucets": {},
        "Fixtures": {},
        "Vanities": {}
    },
    "Building Materials": {
        "Concrete": {},
        "Fencing": {},
        "Gypsum": {},
        "Insulation": {},
        "Insulssdation": {}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

This might do the trick:

input = [{"FirstCategory":"Bath","SecondCategory":"Bath     Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Fixtures","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Vanities","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Concrete","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Fencing","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Gypsum","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulation","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulssdation","ThirdCategory":""}];

function reducer (prev, val) {
    v1 = val["FirstCategory"]
    v2 = val["SecondCategory"]
    if (!(v1 in prev)) { prev[v1] = {}; }
    if (!(v2 in prev[v1])) { prev[v1][v2] = [];}
    prev[v1][v2].push(val["ThirdCategory"]);
    return prev;
}

output = input.reduce(reducer, {});

console.log(input);
console.log(output);

Output:

{ Bath: 
   { 'Bath Accessories': [ '' ],
     Faucets: [ '' ],
     Fixtures: [ '' ],
     Vanities: [ '' ] },
  'Building Materials': 
   { Concrete: [ '' ],
     Fencing: [ '' ],
     Gypsum: [ '' ],
     Insulation: [ '' ],
     Insulssdation: [ '' ] } }

2 Comments

Seriously nice solution .... but Caution! Array.reduce() is an ECMAScript 5 addition. Up to date Chrome, FF, Opera, Safari, and IE9 will be OK but IE6/7/8 will need the workaround script. Read all about it here
@RudolfMühlbauer : Thanxs dude :)
1

Try this :

var formattedData = {};
$.each(data, function(i, item) {
    if(!formattedData[item.FirstCategory]) {
        formattedData[item.FirstCategory] = {};
    }
    if(!formattedData[item.FirstCategory][item.SecondCategory]) {
        formattedData[item.FirstCategory][item.SecondCategory] = [];
    }
    formattedData[item.FirstCategory][item.SecondCategory].push(item.ThirdCategory);
});

The resulting object will be of the following structure :

var formattedData = {
    'Bath': {
        'Bath Accessories': [
            'Non-slip Bath Mat'
        ],
        'Faucets': [
            'Brass Fawcet (Pair)',
            'Chrome Fawcet (Pair)',
            'Gold Fawcet (Monoblock)'
        ],
        'Fixtures': [
            'xxx',
            'yyy',
            'zzz'
        ],
        //etc.
        //etc.
    }
};

DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.