Skip to content
Advertisement

how to create object tree from string in java script

Hi In javascript I have to create object tree from a string as below

“group1:node1:properties,group1:node2:properties,group2:node2:properties,group2:node3:properties,group2:node1:properties,group3:node2:properties”.

In this, properties are also : seperated,

I require object tree as below

group1
   node1
     properties
   node2
     properties
group2
   node2
     properties
   node3
     properties
   node1
     properties
group3
   node2
     properties

can any body tell me what is the best way to do that with example.

Advertisement

Answer

Although it seems like a school exercise…I think you need to take a look at the split() method. First split on the comma (,), then the colon (:). For example..

Look at this: http://jsfiddle.net/T852c/

var str = 'group1:node1:properties,group1:node2:properties,group2:node2:properties,group2:node3:properties,group2:node1:properties,group3:node2:properties';

var result ={},
    groups = str.split(','),
    groupsCount = groups.length; 

for(var i=groupsCount; i--;){
    var groupStr = groups[i],
        split = groupStr.split(':'),
        groupKey = split[0],
        nodeKey = split[1],
        properties = split[2],
        group = result[groupKey] || (result[groupKey] = {}),
        node = group[nodeKey] || (group[nodeKey] = {});
    
    node[properties] = { foo: 'bar' };    
}

console.log(result);

It might not be exactly what you are looking for but it might help to get you started. Good luck!

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement