Write a function that counts the number of times a value occurs in an object.

PHOTO EMBED

Fri Jun 04 2021 17:10:46 GMT+0000 (Coordinated Universal Time)

Saved by @ejiwen #javascript

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
content_copyCOPY