1

I'm trying to loop over a tree of bookmarks (sorted into folders and subfolders), and use their 'path' to create a list of tags for each folder, e.g. - a bookmark stored in 'Dev' > 'JS' > 'Blogs' would be have the tags mapped as ['Dev, 'JS, 'Blogs']

The structure's Chrome's default one using chrome.bookmarks.getTree, which looks like this:

[{
    'title' : '',
    children : [{
           'title' : 'a title',
           'url' : 'http://www.example.com'
       },
       {
           'title' : 'a folder category',
           'children' : [{...}]
        },
    }]
}];

...and my code is:

function processTreeNodes(tree, tags) {
    console.log(tags);
    var t = tags || [];
    for (var i=0; i < tree.length; i++) {
        processNode(tree[i], t);
    }
}


function processNode(n, tags) {
    if(n.children) {
        tags.push(n.title);
        //It's a group, loop over it
        processTreeNodes(n.children, tags);
    } else { 
        //Do something with the bookmark
    }
}

chrome.bookmarks.get(function(bmTree) {
    processTreeNodes(bmTree);
});

What I'd expect is for the console.log to show

[ 'category1', 'subcat1', ...]

and then

['category2, 'subcatA', ...]

What I end up with by the end is

['category1, 'subcat1', ..., 'category2', 'subcatA', ...]

It goes through and pulls all the info out, but it seems to me that when I step back up the stack the arguments for that 'level' haven't been saved.. I think it may be something to do with recursion / closures perhaps, but I'm lost!

Sorry if this makes no sense, I'm struggling to get my head round it as it is, let me know and I can try to explain further if necessary!

1
  • @alnorth29 a mistake! I've edited it now, whoops! Commented Sep 27, 2012 at 14:58

1 Answer 1

2

It looks like you're only ever creating one array and then are passing that around to all your recursive subfunctions. I'll leave you to write the code, but it looks like you'll need to clone your array at each point in the hierarchy so that you're passing a reference to a fresh object, rather than the same one all the time.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was exactly it, I'm sorted now!

Your Answer

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.