1

I have an object like below

var obj = [
    { name : ["a", "x", "1"] , d : [1,2,3] },
    { name : ["a", "x", "2"] , d : [1,2,3] },
    { name : ["a", "y", "3"] , d : [1,2,3] },
    { name : ["a", "y", "4"] , d : [1,2,3] },
    { name : ["a", "z", "5"] , d : [1,2,3] },
    { name : ["a", "z", "6"] , d : [1,2,3] },
    { name : ["b", "x", "7"] , d : [1,2,3] },
    { name : ["b", "x", "9"] , d : [1,2,3] }
];

Above name array length could be any.. I need to group the array like below

formatted = {
    a : {
      x : {
         1 : [1,2,3],
         2 : [1,2,3]
      },
      y : {
         3 : [1,2,3],
         4 : [1,2,3]
      },
      z : {
         5 : [1,2,3],
         6 : [1,2,3]
      }
    },
    b : {
      x : {
         7 : [1,2,3],
         8 : [1,2,3]
      }
    }
}

Is there any algorithm available for this. Please help me implement this logic.

Exception
  • 8,111
  • 22
  • 85
  • 136
  • Show us code of what you have tried so far? – KooiInc Jun 19 '13 at 08:42
  • Have a look at this question: [Javascript: How to set object property given its string name](http://stackoverflow.com/q/13719593/218196). It should be easy to adapt. *edit:* Actually, there is nothing to adapt, you can directly use the proposed solution in the accepted answer. You just have to iterate over your data. – Felix Kling Jun 19 '13 at 08:43
  • @FelixKling Thanks for the code. I have seen that code when I have started programming :). I just placed the question here so that atleast I can get an idea of how to implement. – Exception Jun 19 '13 at 08:44
  • I don't understand. That answer answers your question as well. Why create this question if you've already seen the answer? – Felix Kling Jun 19 '13 at 08:47
  • @FelixKling I am sorry. Small sort of misunderstanding. I am trying to solve that way.. will update if I am done – Exception Jun 19 '13 at 08:55

2 Answers2

0

try something like

var formatted = {}, inner, i, j;

for(i = 0; i < obj.length; i++){
   expand(formatted, obj[i].name, obj[i].d)
}

function expand(obj, array, value){
    var key, temp;
    if(array.length == 1){
        obj[array.shift()] = value;
    } else {
        key = array.shift();
        temp = obj[key] = obj[key] || {};
        expand(temp, array, value)
    }
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

This function from has solved my problem. Thanks Feliz Kling for the suggestion

function setToValue(obj, value, path) {
    var parent = obj;
    for (var i = 0; i < path.length - 1; i += 1) {
        parent[path[i]] = parent[path[i]] || {}
        parent = parent[path[i]];
    }
    parent[path[path.length-1]] = value;
} 
Exception
  • 8,111
  • 22
  • 85
  • 136