w3jimmy w3jimmy - 7 months ago 52
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 (

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

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


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

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


        _.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.