简体   繁体   中英

Iterating through the dictionary from json response

My json view:

def validate_categories(request):
    obj = request.GET.get('categories', '')
    import json
    obj: list[int] = json.loads(obj)
    qs = Institution.objects.filter(categories__in=obj)

    return JsonResponse({institution.name: institution.id for institution in qs})

My Ajax:

  var catArrIdString = JSON.stringify(catArrIdInt)
  if (catArrId.length > 0) {
    $.ajax({
      type: "GET",
      url: "/ajax/validate_categories/",
      dataType: "json",
      data: {
        "categories": catArrIdString
      }
    }).done(function(institutionsByName) {
      for (const [key, value] in Object.entries(institutionsByName)){
        console.log(`${key}: ${value}`);
      }
    })
    .fail(function(e) {
      alert( "error" );
      console.log(e)
    })
  }

Then i have a dict like: "Institution name": Institution Id

How can i iterate through it in javascript and use InnerHTML to put each of institution with its name and ID into a DIV?

You can use Object.entries for iterate using usual loop

 const dictionary = { "name1": 1, "name2": 2, "name3": 3, }; document.body.innerHTML = Object.entries(dictionary).map(([key,val]) => `<div>${key}: ${val}</div>`).join('<br/>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM