"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Flatten Nested Objects with a One-Line Solution?

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

Published on 2024-11-09
Browse:458

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

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.

Release Statement This article is reprinted at: 1729573516 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3