Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!