This is what I am asked for:
We are going to debug a function that takes in an object, and a target value. This function will iterate over the object's values, and attempt to locate the target value. If the value is found, the function should return the name of the key where the value in question is located, and if not, the function should return -1. Below is an example of the code running, assuming that you will have debugged the described function: keyOfObjectValue:
function keyOfObjectValue(object, target) {
for (var key in object) {
if (object[key] === target) {
return key;
} else {
return -1;
}
}
}
var result1 = keyOfObjectValue({cucumbers: 14, carrots: 20, peas: 400}, 20);
console.log('should log "carrots":', result1);
This is what I did (which is not debugging but rather changing all the code instead: There must be an easier way but I could not find it...
function keyOfObjectValue(object, target){
let allKeys=Object.values(object);
console.log(allKeys)
let result= allKeys.find(element=>element==target)
let result2=Object.keys(object).find(key => object[key] === result)
console.log(result);
console.log(result2);
if (result !==undefined){
return result2;
}else
return -1
}
var result1 = keyOfObjectValue({cucumbers: 14, carrots: 20, peas: 400}, 20);
console.log('should log "carrots":', result1);
function keyOfObjectValue(object, target) {
let passedKey = ""
for (var key in object) {
if (object[key] === target) {
passedKey = key
}
}
if(passedKey === ""){return -1}else{return passedKey}
}
var result1 = keyOfObjectValue({cucumbers: 14, carrots: 20, peas: 400}, 20);
console.log('should log "carrots":', result1);