Search code examples
javascriptjavascript-objects

Return specific object value as a string in a function


I'm trying to return an specific value as a string, but I end up getting the value in an array. Instead of getting 'unknown', I get ['u', 'n', 'k', 'n', 'o', 'w', 'n']

Challenge: Create a function findWaldo that accepts an object and returns the value associated with the key 'Waldo'. If the key 'Waldo' is not found, the function should return 'Where's Waldo?'

My code:

function findWaldo(obj) {

  let values = Object.keys(obj);

  if (values.includes('Waldo')) {
    return Object.values(obj.Waldo);
  } else {
    return 'Where\'s Waldo?';
  }
};


// Uncomment these to check your work!
const DC = {
  'Bruce': 'Wayne',
  'Harley': 'Quinn'
}
const supernatural = {
  'Sam': 'Winchester',
  'Dean': 'Winchester',
  'Waldo': 'unknown'
}

console.log(findWaldo(DC)) // should log: 'Where's Waldo?'
console.log(findWaldo(supernatural)) // should log: 'unknown'


Solution

    • In your code return Object.values(obj.Waldo);, obj.Waldo has some string as its value.
    • And Object.values() method returns array of a given object's.
    • That's why it's returning ```['U','n','k','n','o',w'], instead of "Unknown" as a direct string.
    • If you just return obj.Waldo, than you will receive your desire output.
    • Now just to modify your code, I will show you my approach.
    • You can access Object's property in two, one with .[dot] notation and another with Object["Key"]. -Object["Key"] will return undefind if no value found for given string key value, so this will help you to create your logic.

    function findWaldo(obj) {
      if (obj['Waldo']) { // check if we have value
        return obj['Waldo'];
      } else {
        return 'Where\'s Waldo?';
      }
    };
    
    
    const DC = {
      'Bruce': 'Wayne',
      'Harley': 'Quinn'
    }
    const supernatural = {
      'Sam': 'Winchester',
      'Dean': 'Winchester',
      'Waldo': 'unknown'
    }
    
    console.log(findWaldo(DC))
    console.log(findWaldo(supernatural))