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'
CodePudding user response:
The Object.values() method returns an array of a given object's own enumerable string-keyed property values.
hence the output of unknown in array.
Object.values(object)
returns values of object in array while Object.values(string)
returns string split in a array
function findWaldo(obj) {
let values = Object.keys(obj);
if (values.includes('Waldo')) {
return 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'
CodePudding user response:
As the comment said: return obj.Waldo;
but it's simpler to just filter the keys and use the key to return the value or unknown:
const findWaldo = (name,obj) => obj[Object.keys(obj).filter(key => key===name)] || '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('Waldo',DC)) // should log: 'Where's Waldo?'
console.log(findWaldo('Waldo',supernatural)) // should log: 'unknown'
console.log(findWaldo('Bruce',DC)) // should log: Wayne