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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With