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

684
Visualizações
JavaScript: How to get parent object key by child object value?

can you help me to make a function that will be able to find parent object key by child object value?

This is object structure:

const mainObject = {
  FIRST: {
    key1: 'value1',
    key2: 'value2',
  },
  SECOND: {
    key3: 'value3',
    key4: 'value4',
  },
};

I tried to use this function:

function getKeyByValue(object, value) {
  return Object.keys(object).find((key) => object[key] === value);
}

but if I run getKeyByValue(mainObject, 'value4') it returns undefined.

Can someone help how I can improve getKeyByValue function to get the parent key (I need to get 'SECOND' name)?

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

0

Doing it recursively is an option

let path = [];

let parent = '';

function getParent(path, json, value) {
    for (var key in json) {
        if (typeof json[key] === 'object') {
            path.push(key.toString());
            getParent(path, json[key], value);
            path.pop();
        } else {
            if (json[key] == value) {
               parent = path[0];
            }
        }
    }
}

const mainObject = {
  FIRST: {
    key1: 'value1',
    key2: 'value2',
  },
  SECOND: {
    key3: 'value3',
    key4: 'value4',
  },
};

getParent(path, mainObject, 'value4');

console.log(parent);

about 4 years ago · Juan Pablo Isaza Relatório

0

your problem is that you check the wrong keys (objects)

const mainObject = {
  FIRST: {
    key1: 'value1',
    key2: 'value2',
  },
  SECOND: {
    key3: 'value3',
    key4: 'value4',
  },
};

function getKeyByValue(object, value) {
  //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys.
  console.log(Object.keys(object));
  return Object.keys(object).find((key) => Object.keys(object[key]).some((key2) => object[key][key2] === value));
}

//you can also do this and check directly the values
function getKeyByValue2(object, value) {
  //you can see that the first keys are for the first objects (first and second) this method doesnt give nested keys.
  console.log(Object.keys(object));
  return Object.keys(object).find((key) => Object.values(object[key]).indexOf(value) > -1);
}

console.log(getKeyByValue(mainObject, 'value4'));
console.log(getKeyByValue2(mainObject, 'value4'));

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