Home >Web Front-end >JS Tutorial >How to Flatten Nested Objects with a One-Line Solution?
One-Line Solution to Flatten Nested Objects
In the realm of data manipulation, flattening nested objects is a common task. You may need to transform a complex object with multiple levels of nesting into a simpler one with a single level of keys and values. One efficient approach is to utilize a concise one-liner:
Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
Let's break down this one-liner:
To use this one-liner, simply pass your nested object into the yourObject placeholder. The resulting flattened object will be accessible as the output of the expression.
The above is the detailed content of How to Flatten Nested Objects with a One-Line Solution?. For more information, please follow other related articles on the PHP Chinese website!