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

130
Vistas
Javascript Object get properties from lowest level

I want to know whats the best way to simplify a object so that it only contains the properties from the lowest level of the actual object. I will explain by the following example:

Starting Object

const start = {
    a: 1,
    b: {
        c: 2,
        d: 3
    },
    e: 4,
    f:{
        g: 5
    }
}

Wanted Object

const wanted = {
    a: 1,
    c: 2,
    d: 3,
    e: 4, 
    g: 5
}



I generally know how to do it, but it seems very lavish for large objects. Thus, I do not want to write:
const simplified = {
    a: start.a,
    c: start.b.c,
    d: start.b.d,
    e: start.e,
    g: start.f.g
}

Apparently, destructuring an object inside another object is not possible, but it would also help if I can get the children of the parent objects easier, somehow like that:

const simplified = {
    a: start.a,
    //start.b.children?
    e: start.e,
    //start.f.children?
}

I also want to avoid to create duplicates of the variables outside the object creation with destructuring.




What is the best practice for restructuring an object in such way?

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

0

You can simply create a recursive function that will add property to your result only if the current value is not of the object type, and if it is then pass it to another recursive call.

const start = {"a":1,"b":{"c":2,"d":3},"e":4,"f":{"g":5}}

function flatten(data) {
  return Object.entries(data).reduce((r, [k, v]) => {
    if (typeof v === 'object') Object.assign(r, flatten(v))
    else r[k] = v
    return r
  }, {})
}

const result = flatten(start)
console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could map either the object or the nested parts.

function flat(object) {
    return Object.assign({}, ...Object
        .entries(object)
        .map(([k, v]) => v && typeof v === 'object'
            ? flat(v)
            : { [k]: v }
        ));
}

console.log(flat({ a: 1, b: { c: 2, d: 3 }, e: 4, f:{ g: 5 } }));

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