Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Debugging exercise-finding object's values but returning object's key

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);

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!