-1

Hi how can i handle this json response from ajax

{"suivi":5,
"mail":8,
"listSuivi":{
      "0":{"dossier":"IWE123123","refunds_count":1},
      "1":{"dossier":"IM00000009","refunds_count":2}
   }
 }

i can access to suivi and mail doing this

    success: function(data){

      $('#suivi').html(data.mail+" +");
      $('#mail').html(data.suivi+" +");
    }

but how can i obtain the list of dossiers (listSuivi)? Thx a lot

Marco Bozzola
  • 179
  • 1
  • 3
  • 17
  • Does this answer your question? [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Reyno Sep 28 '20 at 11:20
  • 1
    Note that despite its name `listSuivi` is not a list, it is a map with the keys being string representations of integers. – luk2302 Sep 28 '20 at 11:21
  • ah ok so i need also to change the name to be more precise? – Marco Bozzola Sep 28 '20 at 11:29
  • `Object.values(data.listSuivi).map(s => s.dossier)` ? – adiga Sep 28 '20 at 11:33
  • i can access to the first element doing this data["listSuivi"][0]["dossier"] but how can loop ? – Marco Bozzola Sep 28 '20 at 11:38

1 Answers1

1

You can loop over the items with a for loop.

Some options are a for ... in loop:

const data = {
  "suivi":5,
  "mail":8,
  "listSuivi":{
    "0":{"dossier":"IWE123123","refunds_count":1},
    "1":{"dossier":"IM00000009","refunds_count":2}
  }
};

// For ... in loop
for(const key in data.listSuivi) {
  const item = data.listSuivi[key];
  
  console.log("Object: ", item);
  console.log("Dossier:", item.dossier);
  console.log("Refunds:", item.refunds_count);
}

Or a for ... of loop in combination with Object.values

const data = {
  "suivi":5,
  "mail":8,
  "listSuivi":{
    "0":{"dossier":"IWE123123","refunds_count":1},
    "1":{"dossier":"IM00000009","refunds_count":2}
  }
};

// For ... of loop with Object.values
for(const item of Object.values(data.listSuivi)) {
  console.log("Object: ", item);
  console.log("Dossier:", item.dossier);
  console.log("Refunds:", item.refunds_count);
}
Reyno
  • 6,119
  • 18
  • 27