Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda