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

80
Vistas
Deep search is object in javascript

I am trying to search any pairs key:value in an object in JavaScript, and return the sub-object it belongs to.

What I have done so far doesn’t return my object as expected and I can’t find why.

function searchSheet(obj, keyName, valName) {
  let found
  for (prop in obj) {
    if (typeof obj[prop] == "object") {
      searchSheet(obj[prop], keyName, valName);
    } else {
      if (prop === keyName && obj[prop] === valName) {
        found = obj
        console.log(found);
        // found is logged correctly here
        return found
        // …but nothing is returned here
      }
    }
  }
}
let sheet = {
  "config": {},
  "patterns": {
    "id": 0,
    "type": "pattern",
    "startTime": 1652193369859,
    "synth": "tic",
    "keys": [{
        "id": 1,
        "type": "key",
        "keyCode": 73,
        "startTime": 1652193369960,
        "note": 730,
        "offset": "12.1"
      },
      {
        "id": 2,
        "type": "key",
        "keyCode": 82,
        "startTime": 1652193370371,
        "note": 820,
        "offset": "61.2"
      }
    ],
    "endTime": 1652193370695,
    "duration": 836,
    "loop": 35
  }
}
console.log(
  searchSheet(sheet, "keyCode", 82) // undefined
)  

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Ian Brindley's comment is partly correct. You are discarding the return value of the recursive call. You can fix your code by changing this

if (typeof obj[prop] == "object") {
  searchSheet(obj[prop], keyName, valName);
} else { //...

to this

if (typeof obj[prop] == "object") {
   let objectFound = searchSheet(obj[prop], keyName, valName);
   if (objectFound !== undefined) return objectFound
} else { //...

There are other approaches, particularly ones using a nested helper function.

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