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 :

Somme tableau d'objet


Sujet :

JavaScript

  1. #1
    Candidat au Club
    Femme Profil pro
    Chef de projet MOA
    Inscrit en
    Janvier 2021
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 47
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Distribution

    Informations forums :
    Inscription : Janvier 2021
    Messages : 3
    Points : 2
    Points
    2
    Par défaut Somme tableau d'objet
    Bonjour

    je suis en lecture un autre fichier de type json qui contient différente données

    exemple
    Code JSON : 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
    { 
    "stock" : [
           { 
           "Itemid":12,
           "location": "Lyon",
           "quantity": 12
          },
         { 
         "Itemid":12,
         "location": "Lyon",
         "quantity": 14
         },
        { 
        "Itemid":12
        "location": "Brest",
        "quantity": 12
        }
       ]
    }

    Je cherche à faire la somme des quantité et avoir une seule ligne par article/location.

    Il y a très longtemps que je n'ai pas développé... et je n'arrive pas à faire ma somme.

    j'ai fait un bout de code
    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
     let quantitySite = {
            ItemId;"",
            InventSiteId:"",
            InventLocationId:""
            Quantity:0 ;
            }
        let StockEntrepot = [quantitySite] 
     
       for (let i=0 ; stock.length ; i++)
    {
       let current=quantitySite ;
     
       if (StockEntrepot.indexOf(current) === -1)
              StockEntrepot.push(current)
       else {
        let Ind = StockEntrepot.indexOf(current) 
          StockEntrepot[Ind].Quantity =+ current.quantity
    }
     
    }
    Mais ça ne fonctionne pas...

    Est-ce que vous avez une idée ?

    Merci

  2. #2
    Expert confirmé
    Avatar de Doksuri
    Profil pro
    Développeur Web
    Inscrit en
    Juin 2006
    Messages
    2 451
    Détails du profil
    Informations personnelles :
    Âge : 54
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Juin 2006
    Messages : 2 451
    Points : 4 600
    Points
    4 600
    Par défaut
    Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    let total = 0;
    taDataJson.stock.map(x => { total+= x.quantity; });
    console.log(total);
    c'est ca que tu veux ?
    La forme des pyramides prouve que l'Homme a toujours tendance a en faire de moins en moins.

    Venez discuter sur le Chat de Développez !

  3. #3
    Expert confirmé
    Avatar de javatwister
    Homme Profil pro
    danseur
    Inscrit en
    Août 2003
    Messages
    3 681
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : danseur

    Informations forums :
    Inscription : Août 2003
    Messages : 3 681
    Points : 5 221
    Points
    5 221
    Par défaut
    et l'équivalent:
    Code javascript : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    let total=JSon.stock.reduce((x,y) => x+y.quantity,0);
    console.log(total);

  4. #4
    Candidat au Club
    Femme Profil pro
    Chef de projet MOA
    Inscrit en
    Janvier 2021
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 47
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Distribution

    Informations forums :
    Inscription : Janvier 2021
    Messages : 3
    Points : 2
    Points
    2
    Par défaut
    Bonjour,

    en fait, je souhaite retourner un json avec une seule occurrence exemple pour itemid,location

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    "stock" : [
           { 
           "Itemid":12,
           "location": "Lyon",
           "quantity": 36
          },
        { 
        "Itemid":12
        "location": "Brest",
        "quantity": 12
        }
    j'ai l'impression que indexof ne fonctionne pas pour un object de type json.

  5. #5
    Expert confirmé
    Avatar de javatwister
    Homme Profil pro
    danseur
    Inscrit en
    Août 2003
    Messages
    3 681
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : danseur

    Informations forums :
    Inscription : Août 2003
    Messages : 3 681
    Points : 5 221
    Points
    5 221
    Par défaut
    Le truc gênant, c'est que tes "Itemid" soient identiques;

  6. #6
    Expert confirmé
    Avatar de javatwister
    Homme Profil pro
    danseur
    Inscrit en
    Août 2003
    Messages
    3 681
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : danseur

    Informations forums :
    Inscription : Août 2003
    Messages : 3 681
    Points : 5 221
    Points
    5 221

  7. #7
    Candidat au Club
    Femme Profil pro
    Chef de projet MOA
    Inscrit en
    Janvier 2021
    Messages
    3
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Âge : 47
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Chef de projet MOA
    Secteur : Distribution

    Informations forums :
    Inscription : Janvier 2021
    Messages : 3
    Points : 2
    Points
    2
    Par défaut
    Merci,

    J'ai fait un truc que je trouve moche, mais, qui fonctionne.
    J'ai un peu de mal à comprendre, quand j'exécute dans un soap standard, j'ai un xml.

    Code XML : 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
    34
    35
    36
    37
    38
    39
    40
    41
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
       <s:Body>
          <InventoryOnHandServiceFindResponse xmlns="http://schemas.microsoft.com/dynamics/2008/01/services">
             <InventoryOnhand xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/InventoryOnhand">
                <SenderId>tsm</SenderId>
                <InventSum class="entity">
                   <AvailOrdered>19999.60</AvailOrdered>
                   <Closed>No</Closed>
                   <ClosedQty>No</ClosedQty>
                   <InventDimId>STDIM0500106</InventDimId>
                   <ItemId>001820</ItemId>
                   <OnOrder>3280.40</OnOrder>
                   <Ordered>23280.00</Ordered>
                   <PostedValue>-8.11000000000000000000</PostedValue>
                   <InventDim class="entity">
                      <InventColorId>00000</InventColorId>
                      <InventDimId>STDIM0500106</InventDimId>
                      <InventLocationId>SEP402</InventLocationId>
                      <InventSiteId>SL402</InventSiteId>
                      <WMSLocationId>SEP402</WMSLocationId>
                   </InventDim>
                </InventSum>
                <InventSum class="entity">
                   <AvailOrdered>20.00</AvailOrdered>
                   <AvailPhysical>26.80</AvailPhysical>
                   <Closed>No</Closed>
                   <ClosedQty>No</ClosedQty>
                   <InventDimId>STDIM0502200</InventDimId>
                   <ItemId>001820</ItemId>
                   <OnOrder>6.80</OnOrder>
                   <PhysicalInvent>26.80</PhysicalInvent>
                   <PostedQty>26.80</PostedQty>
                   <PostedValue>138.67000000000000000000</PostedValue>
                   <InventDim class="entity">
                      <InventColorId>00000</InventColorId>
                      <InventDimId>STDIM0502200</InventDimId>
                      <InventLocationId>EMG122</InventLocationId>
                      <InventSiteId>SL122</InventSiteId>
                      <WMSLocationId>EMG122</WMSLocationId>
                   </InventDim>
                </InventSum>

    mais en sortie par exemple ItemId est de type tablo... C'est bizarre comme fonctionnement

    dans nodeJs
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
            console.log("retour appel API statusCode=",statusCode) 
            // if OK, parse response to json. Else : force reservation to '9'
            if (statusCode && statusCode === 200) {
                var json = await xml2js.parseStringPromise(body)
                var jsonResponse = await json["s:Envelope"]["s:Body"][0]["InventoryOnHandServiceFindResponse"][0]["InventoryOnhand"][0]
             //   console.log(jsonResponse) 
                result.statusCode = statusCode
                result.serviceResponse = jsonResponse 
            } else {
                result.statusCode = 200
                result.serviceResponse[0].qty = "0"
            }
    je traite un élément de type
    result
    Je suis sur d'avoir le même itemid (J'écrit une api qui renvoi le stock disponible par magasin, je dois faire une somme par magasin)
    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
    34
    35
           for (let i=0 ; i< response.serviceResponse.InventSum.length ; i++)
            {
     
     
                let  inventSum =response.serviceResponse.InventSum[i]
     
     
                jsonDataSet.product = {}
                jsonDataSet.product.item_id = inventSum.ItemId[0]
     
               for (let IndStock=0 ; IndStock < ObjectQuantity.length && stop==0; IndStock++)
                {
          //           console.log("location compare ", ObjectQuantity[IndStock])
                    if (ObjectQuantity[IndStock].site_id == location.site_id  && ObjectQuantity[IndStock].location_id == location.location_id) 
                        {
                            stop=1
               //             console.log("Traitement ETP deja existant ",ObjectQuantity[IndStock].InventSiteId, ObjectQuantity[IndStock].quantity,location.quantity )
                            let QuantityCurrent = parseFloat(location.quantity) 
                            QuantityCurrent += AvailPhysical-AvailOrdered
     
     
                            location.quantity = QuantityCurrent
                            ObjectQuantity[IndStock]=location
                        }
               }
               if (stop === 0)
               {
                ObjectQuantity.push(location)
              // console.log("Ajout ETP")
               //console.log(ObjectQuantity) 
                }
     
            }
     
       }

  8. #8
    Expert confirmé
    Avatar de javatwister
    Homme Profil pro
    danseur
    Inscrit en
    Août 2003
    Messages
    3 681
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Calvados (Basse Normandie)

    Informations professionnelles :
    Activité : danseur

    Informations forums :
    Inscription : Août 2003
    Messages : 3 681
    Points : 5 221
    Points
    5 221
    Par défaut
    Après y a aussi des solutions naïves, artisanales et peu élégantes (comme celle-là)

    Code javascript : 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
    34
    35
    36
    37
    38
    39
    40
    41
    const JSon={ 
    "stock" : [
           { 
           "Itemid":12,
           "location": "Lyon",
           "quantity": 12
          },
         { 
         "Itemid":12,
         "location": "Lyon",
         "quantity": 14
         },
        { 
        "Itemid":12,
        "location": "Brest",
        "quantity": 12
        },
        { 
        "Itemid":14,
        "location": "Brest",
        "quantity": 12
        },
        { 
        "Itemid":12,
        "location": "Brest",
        "quantity": 12
        }
       ]
    }
    console.log(JSON.stringify(JSon.stock))
    const t=[],t2=[];
    JSon.stock.map(v=>{
    	if(!t[v.Itemid+" "+v.location]){
    		t[v.Itemid+" "+v.location]=v.quantity
    	}
    	else t[v.Itemid+" "+v.location]+=v.quantity
    });
    for(i in t){
    	t2.push({"Itemid":i.split(" ")[0],"location":i.split(" ")[1],"quantity":t[i]})
    }
    console.log(JSON.stringify(t2));

Discussions similaires

  1. retour tableau d'objets par service web axis jboss
    Par TrollMaster dans le forum XML/XSL et SOAP
    Réponses: 6
    Dernier message: 27/11/2005, 21h45
  2. Tableau d'objets
    Par moulefrite dans le forum MFC
    Réponses: 7
    Dernier message: 15/06/2004, 14h14
  3. Sauvegarde / Chargement d'un tableau d'objets
    Par Naruto dans le forum Langage
    Réponses: 3
    Dernier message: 18/05/2004, 14h34
  4. [VB6]Tableau d'objet withevents
    Par soazig dans le forum VB 6 et antérieur
    Réponses: 8
    Dernier message: 13/02/2004, 19h44
  5. [VB6] [Syntaxe] Fonction renvoyant un tableau d'objets
    Par Troopers dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 18/10/2002, 15h33

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