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

239
Vistas
How can I get keys from nested object?

I have a javascript object with nested objects inside:

{
    "common": {
      "setting1": "Value 1",
      "setting2": 200,
      "setting3": true,
      "setting6": {
        "key": "value",
        "doge": {
          "wow": ""
        }
      }
    },
    "group1": {
      "baz": "bas",
      "foo": "bar",
      "nest": {
        "key": "value"
      }
    },
    "group2": {
      "abc": 12345,
      "deep": {
        "id": 45
      }
    }
  }

and I have to get all keys as nested array.

I've tried this function :

function getKeys(obj) {                                                                                                                                
  return Object.keys(obj).map((key, keys) => {                                                                                                      
    if (typeof obj[key] !== 'object') return key;                                                                                                    
    return [key, getKeys(obj[key])];                                                                                               
  });                                                                                                                                                  
}    

 

And got this: //

[
  [ 'common', [ 'setting1', 'setting2', 'setting3', [Array] ] ],
  [ 'group1', [ 'baz', 'foo', [Array] ] ],
  [ 'group2', [ 'abc', [Array] ] ]
]

Instead of expected result like this:

    [
  [ 'common', [ 'setting1', 'setting2', 'setting3','setting6', ['key','doge', ['wow']],
  [ 'group1', [ 'baz', 'foo', ['nest', ['key'] ],
  [ 'group2', [ 'abc', 'deep', ['id'] ] ]
    ]

etc.

Help me please

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

0

You can use reduce on Object.entries and create a recursive function.

const data = {"common":{"setting1":"Value 1","setting2":200,"setting3":true,"setting6":{"key":"value","doge":{"wow":""}}},"group1":{"baz":"bas","foo":"bar","nest":{"key":"value"}},"group2":{"abc":12345,"deep":{"id":45}}}

function getKeys(data) {
  return Object.entries(data).reduce((r, [key, value]) => {
    r.push(key)
    if (typeof value === 'object') r.push(getKeys(value))
    return r
  }, [])
}

console.log(getKeys(data))

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this

function getKeys (obj) {
    const keys = Object.keys(obj);
    for (let i = 0; i < keys.length; i++){
        const key = keys[i];
        if (typeof obj[key] === 'object') {
            keys.splice(i+1, 0, getKeys(obj[key]));
            i++;
        }
    }
    return keys
}

result:

'["common",["setting1","setting2","setting3","setting6",["key","doge",["wow"]]],"group1",["baz","foo","nest",["key"]],"group2",["abc","deep",["id"]]]'

Not the most optimised solution probably but should work.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Thanks, both options worked! I just had to add null check in if (typeof obj[key] === 'object') because of the TypeError: Cannot convert undefined or null to object const keys = Object.keys(obj); (one of the values was null and "The typeof null returns 'object' , which is historical bug in JavaScript that may never be fixed.")

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