Home  >  Article  >  Web Front-end  >  How to Flatten Nested Objects with a Single Line of JS Code?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-22 13:17:03123browse

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

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

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

{
  a: 2,
  c: 3
}

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!

Statement:
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