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.
-
4I hope your teacher won't see this :-PjAndy– jAndy2013年10月30日 12:30:01 +00:00Commented Oct 30, 2013 at 12:30
-
Do you need real objects or only an output?CloudyMarble– CloudyMarble2013年10月30日 12:31:25 +00:00Commented Oct 30, 2013 at 12:31
-
I need to create object from which I can access on basis of groupagarwal_achhnera– agarwal_achhnera2013年10月30日 12:32:22 +00:00Commented Oct 30, 2013 at 12:32
1 Answer 1
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!