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

122
Vistas
A function to obtain all leaf node properties of an object in an array of string in javascript

Request you to please help in building a function in javascript to obtain the mentioned output from the input given.

INPUT : An object (possibly a nested object)

example :

{

"message":"string" ,

"data1": {

    "Output1": {

        "leaf1": "abc",

        "Leaf2": "123"

    }

}

"data2": {

    "Output2": {

        "leaf3": "abc",

        "leaf4": "123"

    }

}  

}

OUTPUT : An array of string

Example : str= ["message", "data1.Output1.leaf1", "data1.Output1.leaf2" , "data2.Output2.leaf3","data2.Output2.leaf4"]

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

0

Something like this it will work

const getBranches = (data, prefix=[]) => {
  if (typeof(data) !== 'object') {
    return prefix.join('.')
  }
  return Object.entries(data).flatMap(([k, v]) => getBranches(v, [...prefix, k]))

  }

  const data = {
    "message": "string",
    "data1": {
      "Output1": {
        "leaf1": "abc",
        "Leaf2": "123"
      }
    },
    "data2": {
      "Output2": {
        "leaf3": "abc",
        "leaf4": "123"
      }
    }
  }


console.log(getBranches(data))

Second version

const data = {
  "message": "string",
  "data1": {
    "Output1": {
      "leaf1": [{
        "b": {
          "c": "12"
        }
      }]
    }
  },
  "data2": {
    "Output2": {
      "leaf3": "abc",
      "leaf4": "123"
    }
  }
}
const getBranches = (data, prefix = []) => {
  if (typeof(data) !== 'object') {
    return prefix.join('.')
  }
  return Object.entries(data).flatMap(([k, v]) => Array.isArray(data) ? getBranches(v, [...prefix]) : getBranches(v, [...prefix, k]))
}

console.log(getBranches(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