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

How to Flatten Nested Objects Concisely in JavaScript?

DDD
Release: 2024-10-22 13:36:02
Original
708 people have browsed it

How to Flatten Nested Objects Concisely in JavaScript?

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

into the desired output:

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

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

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

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!

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
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!