Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda