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

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

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 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