Home  >  Article  >  Web Front-end  >  How Do I Flatten Nested Objects in JavaScript with One Line of Code?

How Do I Flatten Nested Objects in JavaScript with One Line of Code?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 13:03:03292browse

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:

  • Conciseness: Achieves object flattening in a single line of code.
  • Versatility: Adaptable to both pure JavaScript and popular libraries like Underscore.
  • Flexibility: Uses a recursive function (_flatten) to handle nested structures dynamically.

Considerations:

  • ES6 Compatibility: Requires support for modern JavaScript features like Object.assign and the spread operator.
  • Zero-Iteration: The recursive function explores all paths in the nested object simultaneously, which can affect performance for large objects.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Bind Variables in PL/SQLNext article:Bind Variables in PL/SQL