I have two objects that look like this:
var cache = {
'39' : { id : 39, name : 'Tom' },
'40' : { id : 40, name : 'David'},
'41' : { id : 41, name : 'Daniel'},
'356': { id :356, grp: 'ROM', fee: '$35'}
}
var tree = {
person : { id : 39 },
memberships : { id : 356 },
}
What I'm trying to do is to write a recursive function that will take the tree object as an argument and generate a data structure that references/links to the corresponding object in the cache object. So finally I must be able to access user 'Tom' like this: tree.person.name.
I'm using recursion for two reasons:
- My actual
treeobject is way more complicated than what I have shown here (it is nested) - It varies depending on the user input and the depth of the tree is unknown
I wrote this recursive function to do the referencing/linking:
var traverse = function (jsonObj) {
if( typeof jsonObj == "object" ) {
if(cache[jsonObj.id]){
jsonObj = Ocache[jsonObj.id];
}
$.each(jsonObj, function(k, v) {
traverse(v);
});
}
else {
// jsonObj is a number or string
}
}
Then I call the function like
traverse(tree);
but when I use the debugger to see my tree object, nothing has changed: tree is the same as before. How do I achieve this and reference/link objects in the cache object?
$.each()is jquery.