Home > Web Front-end > JS Tutorial > body text

How to Flatten Nested Objects with a Single Line of Code?

Patricia Arquette
Release: 2024-10-22 13:05:17
Original
871 people have browsed it

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))
Copy after login

This one-liner can flatten objects with nested properties, converting them into flat objects with one-level properties.

How It Works:

  1. Recursive Function _flatten: The function recursively traverses the object, flattening any nested properties.
  2. Spread Operator (ES6): Inside the _flatten function, the spread operator ... is used to create an array of one-property objects from each property in the object ({[k]: o[k]}).
  3. Concatenation: The Object.keys(o) function returns an array of property names, and the [].concat function is used to concatenate the arrays of one-property objects into a single array.
  4. Object.assign Function (ES6): The Object.assign function is used to combine the flattened arrays of one-property objects into a single, flattened object.

Example:

Using the example object:

{
  a: 2,
  b: {
    c: 3
  }
}
Copy after login

The one-line solution will produce the flattened object:

{
  a: 2,
  c: 3
}
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!