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

55
Visualizações
Get value of the key in deeply nested object

Let's say I have input object like this one:

const obj = {
  deep: {
    someKey: 'someValue1!',
    veryDeep: {
      someOtherKey: 'someOtherValue'
    }
  },
  deep2: {
    aa: 'bba'
  }
}

I want to write a function that will take this object as first argument and key string as second argument. Then it's gonna loop through obj with recursion and find the value and return it. So if I name this function getObjectValueOfKey it will be called like this: getObjectValueOfKey(obj, 'aa') and it will return 'bba'.

I think I'm close with this code:

const getObjectValueOfKey = (obj, key) => {
  const keys = Object.keys(obj)
  for (let currKey of keys) {
    if (typeof obj[currKey] === 'object') {
      getObjectValueOfKey(obj[currKey], key)
    }
    if (currKey === key) {
      return obj[key]
    }
  }
}

const res = getObjectValueOfKey(obj, 'aa')
console.log('res', res)

but for some unknown to me reasons res is undefined.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

you were pretty close, the recursion was good but the problem is related with what all the paths in your code doesn't return, actually the only path that return is when you found the key in the first level of the object, after you made the recursion and found the result but nothing was returned, the code reach the end the of function and javascript return by default undefined if any return is not found, to solve the problem a decide to store the results found in the recursion in a variable and return that value at the end of the function.

const getObjectValueOfKey = (obj, key, found) => {

  const keys = Object.keys(obj);
  let result = undefined;
  result ||= found;
  for (let currKey of keys) {
    if (typeof obj[currKey] === "object") {
      result ||= getObjectValueOfKey(obj[currKey], key, result);
    }
    if (currKey === key) {
      return obj[key];
    }
  }
  return result;
};

const res = getObjectValueOfKey(obj, "aa", undefined);
console.log("res", res);
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