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?
CodePudding user response:
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)
CodePudding user response:
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 } }));