w3jimmy w3jimmy - 23 days ago 8
Javascript Question

DEPTH of javascript recursive function

I'm trying to save a json structure in mongodb, but I'd like to get the depth of recursiveness (

DEPTH
) that each item has when looping through this function. How can I achieve this reusing the following function?:

_.mixin({
importJsonItemsToMongo: function (obj, opt, iterator) {
function recurse (json_item) {
// console.log(`level ${DEPTH}: ${json_item.name}`);
db.collection('json_import_items').insert(json_item);
_.each(json_item.child_items, _.importJsonItemsToMongo);
};
recurse(obj);
}
});
_.each(jsonResponse.child_items, _.importJsonItemsToMongo);

Answer

I don't know how underscore.js does work, but I guess, it can be done like this:

_.mixin({
    importJsonItemsToMongo: function (obj, depth) {
        console.log(`level ${DEPTH}: ${obj.name}`);

        db.collection('json_import_items').insert(obj);

        _.each(obj.child_items, function(x) {
            _.importJsonItemsToMongo(x, depth + 1);
        });
    }
});
_.each(jsonResponse.child_items, function(x) {
    _.importJsonItemsToMongo(x, 0);
});

I have just added a depth argument; and have removed unused arguments, you can add it back, if you need.