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

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

Susan Sarandon
Release: 2024-10-22 13:17:03
Original
122 people have browsed it

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

Flatten Nested Objects with a One-Liner

Flattening nested objects is a common task in programming, and it's even more straightforward with modern JavaScript. Here's a one-line solution that uses the spread operator and Object.assign:

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

How it Works:

This code uses a recursive function, _flatten, which traverses the nested object and creates an array of one-property objects. Each property name is mapped to its corresponding value, and if the value is another object, the function recurses into that object.

The spread operator (...) is used to flatten the array of objects created by _flatten. The resulting array is then passed to Object.assign, which combines all the objects into a single, flattened object.

Example Input and Output:

Consider the following nested object:

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

Running the provided code on this object will produce the flattened result:

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

Note:

This solution uses ES6 features, so you may need to adjust it if you're using an older JavaScript environment.

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