IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JavaScript Discussion :

Transformation d'une liste d'objets


Sujet :

JavaScript

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Mai 2009
    Messages
    48
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2009
    Messages : 48
    Points : 38
    Points
    38
    Par défaut Transformation d'une liste d'objets
    Bonjour,

    Je chercher à convertir une liste d'objet pour avoir en sortie un groupement selon un attribut:

    Input:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    [
      {
        "AtrLibelle": "1",
        "CatLibelle": "Cat 1"
      },
      {
        "AtrLibelle": "2",
        "CatLibelle": "Cat 1"
      },
      {
        "AtrLibelle": "3",
        "CatLibelle": "Cat 1"
      },
      {
        "AtrLibelle": "4",
        "CatLibelle": "Cat 2"
      },
      {
        "AtrLibelle": "5",
        "CatLibelle": "Cat 2"
      },
      {
        "AtrLibelle": "6",
        "CatLibelle": "Cat 3"
      }
    ]
    output

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    [
    	{
    		"CatLibelle": "Cat 1"
    		"Attributs":[{
    			"AtrLibelle": "1",
    			"CatLibelle": "Cat 1"
    		  },{
    			"AtrLibelle": "2",
    			"CatLibelle": "Cat 1"
    		  },{
    			"AtrLibelle": "3",
    			"CatLibelle": "Cat 1"
    		  }
    		]
    	},{
    		"CatLibelle": "Cat 2"
    		"Attributs":[{
    			"AtrLibelle": "4",
    			"CatLibelle": "Cat 2"
    		  },{
    			"AtrLibelle": "5",
    			"CatLibelle": "Cat 2"
    		  }
    		]
    	},{
    		"CatLibelle": "Cat 3"
    		"Attributs":[{
    			"AtrLibelle": "6",
    			"CatLibelle": "Cat 3"
    		  }3
    		]
    	}
    ]
    L'utilisation de la lib underscore (http://underscorejs.org/underscore-min.js) permet de faire cela sauf que les attributs seront groupés et affectés à un champ portant le nom de la catégorie. Hors je cherche à avoir un nom générique (CatLibelle par exemple et non pas cat 1, cat 2 cat 3).

    Merci d'avance

  2. #2
    Expert éminent
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 093
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 093
    Points : 6 754
    Points
    6 754
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    var output = (function () {
      var cats = {};
      var result = [];
     
      input.forEach(function (entry) {
        var libelle = entry.CatLibelle;
        if (!(libelle in cats)) {
          cats[libelle] = { CatLibelle: libelle, Attributs: [] };
        }
        cats[libelle].Attributs.push(entry);
      });
     
      for (var catName in cats) result.push(cats[catName]);
      return result;
    })();
     
    console.table(output);
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

  3. #3
    Rédacteur

    Avatar de autran
    Homme Profil pro
    Développeur Java
    Inscrit en
    Février 2015
    Messages
    1 241
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Var (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2015
    Messages : 1 241
    Points : 7 653
    Points
    7 653
    Billets dans le blog
    55
    Par défaut
    Pour le fun je propose ça toujours en O(n)

    Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var shift = 0;
    var output = input.map(x => ({"CatLibelle" : x.CatLibelle, "Attributs" : [x]}));
    input.forEach((x,i,arr) => {
      if(i < arr.length - 1 && x.CatLibelle === arr[i+1].CatLibelle) {
          output[i-shift].Attributs.push(arr[i+1]);
          output.splice(i-shift+1, 1);
          shift++;
      }
    });
    console.log(output);
    Développeur Java
    Site Web

  4. #4
    Rédacteur/Modérateur

    Avatar de SylvainPV
    Profil pro
    Inscrit en
    Novembre 2012
    Messages
    3 375
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2012
    Messages : 3 375
    Points : 9 944
    Points
    9 944
    Par défaut
    et en ES6:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    const categories = [...new Set(input.map(l=> l.CatLibelle))];
    const output = categories.map(c => ({  CatLibelle: c,  Attributs: input.filter(l=> l.CatLibelle === c) }) );
     
    console.log(JSON.stringify(output, null, "\t"));
    One Web to rule them all

  5. #5
    Expert éminent
    Avatar de Watilin
    Homme Profil pro
    En recherche d'emploi
    Inscrit en
    Juin 2010
    Messages
    3 093
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 35
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : En recherche d'emploi

    Informations forums :
    Inscription : Juin 2010
    Messages : 3 093
    Points : 6 754
    Points
    6 754
    Par défaut
    Citation Envoyé par autran Voir le message
    Bon il y en a d'autres avec reduce et filter en O(1)
    Si tu connais un moyen d’itérer sur un tableau en O(1) je pense que tu as intérêt à le publier dans les revues de recherche informatique, parce que là tu mets direct les algorithmes quantiques à la retraite
    La FAQ JavaScript – Les cours JavaScript
    Touche F12 = la console → l’outil indispensable pour développer en JavaScript !

Discussions similaires

  1. Réponses: 0
    Dernier message: 21/11/2013, 17h35
  2. Créer une liste d'objets statiques dans une classe
    Par crossbowman dans le forum C++
    Réponses: 3
    Dernier message: 13/03/2006, 09h11
  3. methode qui retourne une liste d'objets du meme type
    Par anoukhan dans le forum Oracle
    Réponses: 8
    Dernier message: 12/01/2006, 18h38
  4. Tri d'une liste d'objet CObList
    Par cjacquel dans le forum MFC
    Réponses: 1
    Dernier message: 13/07/2005, 13h50
  5. [MFC] Retourner une liste d'objets
    Par 1cado dans le forum MFC
    Réponses: 10
    Dernier message: 28/07/2003, 12h11

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo