Home > Article > Web Front-end > How Do I Flatten Nested Objects in JavaScript with One Line of Code?
Flattening Nested Objects with a One-Liner
In JavaScript, the task of flattening nested objects arises frequently. This operation involves transforming a complex object with nested levels into a single-level object. While there are various approaches to achieving this, we'll delve into a one-line solution that leverages modern JavaScript features.
The provided snippet efficiently flattens nested objects using the Object.assign() method. It combines an array of one-property objects created through a recursive function (_flatten). This function traverses each key in the input object and either calls itself if the value is another object or creates an object with a single property-value pair otherwise.
Implementation:
Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
Example:
Consider the nested object:
{ a:2, b: { c:3 } }
Flattening this object yields:
{ a:2, c:3 }
Advantages:
Considerations:
The above is the detailed content of How Do I Flatten Nested Objects in JavaScript with One Line of Code?. For more information, please follow other related articles on the PHP Chinese website!