Home > Article > Web Front-end > How to Flatten Nested Objects with a Single Line of Code?
Flattening Nested Objects with a One-Liner
To flatten nested objects, you can employ the following one-line solution:
Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
This one-liner can flatten objects with nested properties, converting them into flat objects with one-level properties.
How It Works:
Example:
Using the example object:
{ a: 2, b: { c: 3 } }
The one-line solution will produce the flattened object:
{ a: 2, c: 3 }
The above is the detailed content of How to Flatten Nested Objects with a Single Line of Code?. For more information, please follow other related articles on the PHP Chinese website!