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

How to Flatten Nested Objects with a One-Line Solution?

Mary-Kate Olsen
Release: 2024-10-22 16:22:02
Original
584 people have browsed it

How to Flatten Nested Objects with a One-Line Solution?

One-Line Solution to Flatten Nested Objects

In the realm of data manipulation, flattening nested objects is a common task. You may need to transform a complex object with multiple levels of nesting into a simpler one with a single level of keys and values. One efficient approach is to utilize a concise one-liner:

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

Let's break down this one-liner:

  • The premise is to recursively traverse the object and construct an array of nested one-property objects.
  • The Object.assign method is then used to combine these objects into a single flattened object.
  • The _flatten function is a recursive helper that descends into nested objects, creating one-property objects based on key-value pairs.
  • This process continues until all nested objects have been flattened.

To use this one-liner, simply pass your nested object into the yourObject placeholder. The resulting flattened object will be accessible as the output of the expression.

The above is the detailed content of How to Flatten Nested Objects with a One-Line Solution?. 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!