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

99
Visualizações
Getting last appearance of a deeply nested value by specified property

I've got this object as example:

const obj = {
    group: {
        data: {
            data: [
                {
                    id: null,
                    value: 'someValue',
                    data: 'someData'
                }
            ]
        }
    }
};

My goal is to get a value by propery name.

In this case I would like to get the value of the data propery, but the last appearance of it.

Meaning the expected output is:

someData

However, I'm using this recursive function to retreive it:

const findVal = (obj, propertyToExtract) => {
  if (obj && obj[propertyToExtract]) return obj[propertyToExtract];

  for (let key in obj) {
      if (typeof obj[key] === 'object') {
          const value = findVal(obj[key], propertyToExtract);
          if (value) return value;
      }
  }
  return false;
};

Which gives me the first appearance of data, meaning:

data: [
    {
       value: 'someValue',
       data: 'someData'
    }
]

How can I get the wanted result?

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

0

one way can be to recursively flat the object and just get the wanted index (here data)

const obj = {
group: {
    data: {
        data: [
            {
                id: null,
                value: 'someValue',
                data: 'someData'
            }
        ]
    }
}
};

function deepFlat(obj) {
  let flatObj = {};
  flat(obj,flatObj);
  console.log(flatObj);
  return flatObj;
}

function flat(toFlat, flatObj) {
  Object.entries(toFlat).forEach(elem => {
    if (elem[1] && typeof elem[1] === 'object') {
     flat(elem[1], flatObj);
    } else {
      flatObj[elem[0]] = elem[1];
    }
  });
}

let result = deepFlat(obj);
console.log(result['data']);

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