Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through an object which has nested objects in nodeJs

I have a javascript object with multiple nested objects like this :

 var stats = {
     bookServed: {
         redis: 90,
         s3: 90,
         signedUrl: 70
     },
     errors: {
         redis: {
             bookService: 70,
             mapi: 50,
             capi: 30
         },
         AWS: {
             signedUrl: 70,
             downloadBook: 50,
             searchBook: 10
         },
         decryption: 60
     }
 };

What would be the cleanest way to iterate through all its properties and set each value to 0 for instance. I wrote something like this

 for (var property in stats) {
     if (stats.hasOwnProperty(property)) {
         if (typeof property === "object") {
             for (var sub_property in property)
                 if (property.hasOwnProperty(sub_property)) {
                     sub_property = 0
                 }
         } else {
             property = 0;
         }
     }
 }

I'm willing to use a library like underscore.js to do the task properly.

like image 725
Amaynut Avatar asked Feb 20 '26 18:02

Amaynut


1 Answers

Relatively simple recursion problem, I would use a function that calls itself when sub objects are found. I would also avoid using a for in loop, and instead use a forEach on the object's keys (it's much faster, and doesn't require a hasOwnProperty check.)

function resetValuesToZero (obj) {
    Object.keys(obj).forEach(function (key) {
        if (typeof obj[key] === 'object') {
            return resetValuesToZero(obj[key]);
        }
        obj[key] = 0;
    });
}

var stats = {
     bookServed: {
         redis: 90,
         s3: 90,
         signedUrl: 70
     },
     errors: {
         redis: {
             bookService: 70,
             mapi: 50,
             capi: 30
         },
         AWS: {
             signedUrl: 70,
             downloadBook: 50,
             searchBook: 10
         },
         decryption: 60
     }
 };

console.log(stats.errors.AWS.signedUrl); // 70
resetValuesToZero(stats);
console.log(stats.errors.AWS.signedUrl); // 0
like image 55
Kevin B Avatar answered Feb 23 '26 07:02

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!