var countValuesInObj = function(obj, value) {
var count = 0;
for ( const property in obj ) {
if( typeof obj[property] === 'object') {
count = count + countValuesInObj(obj[property], value);
}
if(obj[property] === value ) {
return 1; // count = count + 1; // count++;
}
}
return count;
};
var obj = {
'e':{'x':'y'},
't':{
'r':{'e':'r'},
'p':{'y':'r'}
},
'y':'e'
};
console.log(countValuesInObj(obj, 'r')) // 2
console.log(countValuesInObj(obj, 'e')) // 1
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter