This one really got me. Mostly because i spent 40 minutes on mindless looking for ready to take solution.
After checking dozen of lodash methods almost on random hoping it will just work i realized i had to invest some effort ;)
But once you get past the scary bit that "IT CAN GO FOREVER", and realize that recursive function is what you need - it is really trivial.
I needed to parse resulting JSON from chrome extensions API chrome.bookmarks.get and extract folder names and their ids.
Retrieved type is called BookmarkTreeNode.
It is basically simple object with some string and integer props, but one property named'children'
can be an array of nested - children nodes. It is a property of object which usually represent parent folder.
So what we need to do is to check the properties of currently iterated object and first, save folder name and id to our empty array (as this was my goal in the first place) and check if among properties is another object to iterate.
And that's it.
const links = require('./links.json');
let folders = []; // folders will be pushed here
const checkObj = obj => {
if ('dateGroupModified' in obj) // 'dateGroupModified' is present only for folder node
folders.push({ title: obj.title, id: obj.id });
Object.keys(obj).forEach(key => {
if (typeof obj[key] == 'object') checkObj(obj[key]);
});
};
checkObj(links);