tags:

views:

40

answers:

1

Hi I get the following data back from my WCF Data Service (I cut out the metadata)

{
"d" : [
  {"CodeId": 6, "Title": "A Child Sub Item", "Parent":}, 
  {"CodeId": 5, "Title": "Another Root Item", "Parent": -1},
  {"CodeId": 4, "Title": "Child Item", "Parent": 2},
  {"CodeId": 2, "Title": "Root Item", "Parent": -1}
]
}

I am trying to get this into a <ul> style tree with Parent = -1 as root and then the rest as sub items of their parent id's.

Can anyone help me please, preferably in jQuery? I will use this in jstree if someone knows of a better way to do this.

Thanks

A: 
  1. Loop through those objects and convert them to the type jstree likes, while storing them in another object with CodeId as the key and the object as the value. Remember to preserve the Parent attribute
  2. Loop through the object you just created, and for each item:
    1. If it's a root node, add it into a list
    2. If it's not a root node, look up its parent from the object and add it to the parent's child collection
  3. Feed the list you created in 3.1. into jstree
Matti Virkkunen
Thank you very much, I now have a tree structure in JavaScript. I now cannot get jstree to use the data (it wants a file or url to load from) but I will work on that now.
Pieter
This fixed it for me in case someone else ever needs it. List was my 'tree' of objects.$(function () { $("#codeTree").tree({ data: { type: "json" }, callback: { beforedata: function (n, t) { t.settings.data.opts.static = eval(JSON.stringify(List)); } } });});
Pieter
@Pieter: I don't think eval(JSON.stringify(...)) does anything...
Matti Virkkunen
@Matti: It does not work without that. I can only assume that the JSON.stringify changes the object into a json string which then gets turned into a json object which is what is required. I might be doing the list wrong, but it works for me like that.
Pieter
@Pieter: Any JavaScript object *is* a "JSON object". JSON is a subset of JavaScript and I don't think it's a good idea to call anything a "JSON object", unless you're really talking about the serialized string form. I'd examine both the original object and the the serialized-unserialized object in Firebug to find out what's different about them.
Matti Virkkunen
@Matti: Thanks a million for making that clear...I am still rather new to JavaScript objects. I inspected them and they were the same, so I tried setting the data = my objects and it worked. I must have done something wrong the other night. Your help is very much appreciated!
Pieter