Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda