Maison > interface Web > js tutoriel > le corps du texte

Comment aplatir des objets imbriqués avec une seule ligne de code ?

Patricia Arquette
Libérer: 2024-10-22 13:05:17
original
870 Les gens l'ont consulté

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

Flattening Nested Objects with a One-Liner

To flatten nested objects, you can employ the following one-line solution:

Object.assign({}, ...function _flatten(o) { return [].concat(...Object.keys(o).map(k => typeof o[k] === 'object' ? _flatten(o[k]) : ({[k]: o[k]})))}(yourObject))
Copier après la connexion

This one-liner can flatten objects with nested properties, converting them into flat objects with one-level properties.

How It Works:

  1. Recursive Function _flatten: The function recursively traverses the object, flattening any nested properties.
  2. Spread Operator (ES6): Inside the _flatten function, the spread operator ... is used to create an array of one-property objects from each property in the object ({[k]: o[k]}).
  3. Concatenation: The Object.keys(o) function returns an array of property names, and the [].concat function is used to concatenate the arrays of one-property objects into a single array.
  4. Object.assign Function (ES6): The Object.assign function is used to combine the flattened arrays of one-property objects into a single, flattened object.

Example:

Using the example object:

{
  a: 2,
  b: {
    c: 3
  }
}
Copier après la connexion

The one-line solution will produce the flattened object:

{
  a: 2,
  c: 3
}
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!