1

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.

asked Oct 30, 2013 at 12:28
3
  • 4
    I hope your teacher won't see this :-P Commented Oct 30, 2013 at 12:30
  • Do you need real objects or only an output? Commented Oct 30, 2013 at 12:31
  • I need to create object from which I can access on basis of group Commented Oct 30, 2013 at 12:32

1 Answer 1

4

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!

answered Oct 30, 2013 at 12:31
Sign up to request clarification or add additional context in comments.

1 Comment

And when you splitted them, append to the array.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.