Flattening Nested Objects Concisely
Transforming a nested object into a flattened structure is often required in various programming scenarios. For a quick and efficient solution, you can utilize a concise one-liner.
To flatten the provided nested object:
{ a:2, b: { c:3 } }
into the desired output:
{ a:2, c:3 }
Employ the following JavaScript expression:
Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
The core concept behind this approach is to recursively create an array of one-property objects. The Object.keys(o) method retrieves all the keys of the input object o. Each key k is then checked for object type. If typeof o[k] === 'object', the function _flatten is recursively applied to the nested object. Otherwise, it constructs a one-property object with the key k and value o[k].
The [].concat(... syntax combines all these one-property objects into a single array. Finally, Object.assign({}, ...) merges these arrays into the desired flattened output.
For readability, the code can be reformatted into the following:
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 effectively flattens nested objects, providing a concise and efficient solution for your data transformation needs.
The above is the detailed content of How to Flatten Nested Objects Concisely in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!