jqueryeach

jQuery .each() how to use on this object


I getting some JSON and trying to do an .each on the response. I'm unsure how to do that on this object. I'm trying to get the Title and SysID.

enter image description here

Here is my JS:

        var siteURL = _spPageContextInfo.webAbsoluteUrl;;
    $.ajax({
        url: siteURL + "/content/_api/web/lists/getbytitle('topsupportarticles')/items",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (response) {
            if (response.d.results.length > 0) {
            console.log(response);
                    //This section can be used to iterate through data and show it on screen .each should be here
                    console.log(response.d.results[0].Title);
                    $(".js-top-support").html("<li><a href=\"/pages/snDetails.aspx?articleID=KB0010606&sysID=" + response.d.results[0].SysID + 
                    "\" class=\"js-top-support-articles\">" + response.d.results[0].Title + "</a><div class=\"x-editable-menu\"><span class=\"btn-edit\"><span class=\"icon-wrench\"></span></span></div></li>");
            }
        },
        error: function (response) {
            alert("Error: " + response);
        }
    });

Solution

  • You can choose one of these two things.

    1. You can use JSON.parse() method to parse the string as valid json.
    2. Use dataType:"json" which can parse the json string as a valid json automatically.

    To me second approach is better. So, you can do this:

    $.ajax({
      url: siteURL + "/content/_api/web/lists/getbytitle('topsupportarticles')/items",
      method: "GET",
      headers: {
        "Accept": "application/json; odata=verbose"
      },
      dataType:"json", //<------------------------ ADDED DATATYPE HERE
      success: function(response) {
        if (response.d.results.length > 0) {
          console.log(response);
          //This section can be used to iterate through data and show it on screen .each should be here
          console.log(response.d.results[0].Title);
          $(".js-top-support").html("<li><a href=\"/pages/snDetails.aspx?articleID=KB0010606&sysID=" + response.d.results[0].SysID +
            "\" class=\"js-top-support-articles\">" + response.d.results[0].Title + "</a><div class=\"x-editable-menu\"><span class=\"btn-edit\"><span class=\"icon-wrench\"></span></span></div></li>");
        }
      },
      error: function(response) {
        alert("Error: " + response);
      }
    });
    

    But you should note if you have only one object there then you can use response.d.results[0] in here, otherwise use a for loop or $.each() to iterate over the objects in the array.


    As a side note you have two semicolons here:

    var siteURL = _spPageContextInfo.webAbsoluteUrl;;