w3jimmy w3jimmy - 1 year ago 105
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download