0

I am trying to access all my data so that I can append it my html document.

I couldn't reach any of the nested arrays by using evt.locations[i].foo because it would only return the first record.

My goal is to be able to access the variables, I have declared and append them to main_info or secondary_info.

Note: I will obviously be restructuring the number of paragraphs used each time but it is just to see it on the page.

$.each(data.events, function(i, evt) {

    //getting all nested records

    evt.locations.forEach(function(locations, i, array) {

        //location data
        var city = evt.locations[i].city;
        var state = evt.locations[i].state;
        var timeZone = evt.locations[i].timezone;
        var contactPhone = evt.locations[i].contactPhone;
        var contactEmail = evt.locations[i].contactEmail;
        var contactName = evt.locations[i].contactName;
        var address1 = evt.locations[i].address1;
        var address2 = evt.locations[i].address2;
        var postalCode = evt.locations[i].postalCode;

        //hosts
        var host = evt.locations[i].tags.host;
        var specialGuest = evt.locations[i].tags.specialGuest;
        var cohost = evt.locations[i].tags.cohost;


        //tiers
        var tierTitle = evt.locations[i].tiers[i].title;
        var tierDecription = evt.locations[i].tiers[i].decription;
        var tierPrice = evt.locations[i].tiers[i].price;
        var tierRaiser = evt.locations[i].tiers[i].raiser;
        var tierMax = evt.locations[i].tiers[i].maxNum;
        var tierQuantity = evt.locations[i].tiers[i].quantity;

        var shiftStart = evt.locations[i].shifts[i].startDate;
        var shiftEnd = evt.locations[i].shifts[i].endDate;

        //Creating variables for schema found within locations

        console.log(evt.locations[i].city)

        //if equal to null/nan/undefined/""
    });


    var main_info = '<h1>' + evt.name + '</h1>';
    main_info += '<p>' + evt.templateInfo.title + '</p>';
    main_info += '<p>' + evt.description + '</p>';
    main_info += '<p> Date: ' + dateString + " " + timeOfEvent + '</p>';
    main_info += '<button class="eventsButton">View Event Details</button>';


    // only counts first record
    // main_info += '<p class="mainInfo">' + evt.locations[i].city + ',' 
           + evt.locations[i].state +'</p>';


    var secondary_info = '<h1 class="">' + 'hello' + '</h1>';
    secondary_info += '<p class="">' + evt.description + '</p>';
    secondary_info += '<p class="">' + evt.createdDate + '</p>';
    secondary_info += '<p class="">' + evt.createdDate + '</p>';
    secondary_info += '<p class="">' + evt.guestsCanInviteOthers + '</p>';

code in JsBin

Parkash Kumar
  • 4,710
  • 3
  • 23
  • 39
ImJessW
  • 41
  • 6
  • Could you post a sample of your data? Aside from the fact that your variables are not accessible outside of your `forEach` (as answers have already pointed out) the `tiers` bit is probably wrong as you are using `i` for both the location index and tier index. e.g. say you are looking at `evt.locations[6]` the only `tier` you would be able to access would be 6 i.e.`evt.locations[6].tiers[6]` while you probably want `evt.locations[6].tiers[0]` – John C Dec 18 '15 at 09:34

3 Answers3

2

you already ve a ready to be used object from the http call, why parse it again

$(document).ready(function() {
  // Getting all the data from AWS link
  $.ajax({
    url: 'https://s3.amazonaws.com/interview-api-samples/events-results.json',
    cache: false,
    dataType: 'json',
    type: 'GET',
    data: ({
      'events': []
    }),
    success: printEvents,
    error: function(e, xhr) {
      console.log(e);
    }

  });

  function printEvents(events) {

    $.each(events.events, function(i, event) {
      //console.log(i, event);
      var eventStart = event.startDate;
      var myDate = new Date(eventStart);

      var dateString = myDate.getUTCMonth() + "/" + ("0" + (myDate.getUTCDate() + 1)).slice(-2) + "/" + ("0" + myDate.getUTCFullYear()).slice(-2);

      // Converting time from military to standaerd and checking if it is am/pm
      var hours = myDate.getUTCHours();
      var minutes = myDate.getUTCMinutes();

      var timeOfEvent = "" + ((hours > 12) ? hours - 12 : hours);
      timeOfEvent += (minutes < 10) ? ":0" + minutes : ":" + minutes;
      timeOfEvent += (hours >= 12) ? " P.M." : " A.M.";

      var main_info = '<h1>' + event.name + '</h1>';
      main_info += '<p>' + /*event.templateInfo.title*/ "" + '</p>'; //<--- empty
      main_info += '<p>' + event.description + '</p>';
      main_info += '<p> Date: ' + dateString + " " + timeOfEvent + '</p>';
      main_info += '<button class="eventsButton">View Event Details</button>';

      console.log(event.locations);
      $.each(event.locations, function(i, location) {
        // here take what you need es: location.city, location.contactGivenName ....
        $.each(Object.keys(location), function(i, loc) {
          main_info += '<p class="mainInfo">' + loc + ' , ' + location[loc] + '</p>';
        })

        $.each(location.tiers, function(i, tier) {
          // here take what you need es: tier.id, tier.quantity ....
          $.each(Object.keys(tier), function(i, t) {
            main_info += '<p class="mainInfo">' + t + ' , ' + tier[t] + '</p>';
          })
        });
        
        //same here for others nested array elements
      });

      var secondary_info = '<h1 class="">' + 'hello' + '</h1>';
      secondary_info += '<p class="">' + event.description + '</p>';
      secondary_info += '<p class="">' + event.createdDate + '</p>';
      secondary_info += '<p class="">' + event.createdDate + '</p>';
      secondary_info += '<p class="">' + event.guestsCanInviteOthers + '</p>';
      $("div.content").append("<div class=event><div class=main_info>" + main_info + "<div class=secondary_info>" + secondary_info + "<input class=attending type=checkbox>" + "I will attend this event" + "</>" + "</div></div></div>");

    });

  }

  console.log("done");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class=content></div>
Vanojx1
  • 5,574
  • 2
  • 23
  • 37
0

try:

$(document).ready(function(){
// Getting all the data from AWS link
    $.ajax(
    {
        url: 'https://s3.amazonaws.com/interview-api-samples/events-results.json',
        cache: false,
        dataType: 'json',
        type: 'GET',
        data: ({ 'events' : [] }),
        success: hillEvents,
        error: function(e, xhr)
        {
            console.log(e);
        }

    });

    function hillEvents(data)
    {
        $('#hillEvents').html(data.Date);
        $.each(data.events, function(i, evt){

            // converting date and time.

            var eventStart= evt.startDate;
            var myDate = new Date(eventStart);

            // changing myDate to a date string
            var dateString = 
              myDate.getUTCMonth() +"/"+
              ("0" + (myDate.getUTCDate()+1)).slice(-2) +"/"+
              ("0" + myDate.getUTCFullYear()).slice(-2);


            // Converting time from military to standaerd and checking if it is am/pm
            var hours = myDate.getUTCHours();
            var minutes =myDate.getUTCMinutes();

            var timeOfEvent = "" + ((hours >12) ? hours - 12 : hours);
                timeOfEvent += (minutes < 10) ? ":0" + minutes : ":" + minutes;
                timeOfEvent += (hours >= 12) ? " P.M." : " A.M.";



        //getting all nested records


            $.each(evt.locations,function(i,locations) {

                //location data
                var city= locations.city;
                var state= locations.state;
                var timeZone= locations.timezone;
                var contactPhone= locations.contactPhone;
                var contactEmail= locations.contactEmail;
                var contactName= locations.contactName;
                var address1= locations.address1;
                var address2= locations.address2;
                var postalCode= locations.postalCode;

                //hosts
                var host= locations.tags.host;
                var specialGuest=locations.tags.specialGuest;
                var cohost=locations.tags.cohost;


                $.each(locations.tiers,function(i,v){
                var tierTitle= v.title;
                var tierDecription= v.decription;
                var tierPrice=locations.price;
                var tierRaiser=v.raiser;
                var tierMax=v.maxNum;
                var tierQuantity=v.quantity;
                 });
              $.each(locations.shifts,function(i,v){
                var shiftStart= v.startDate;
                var shiftEnd= v.endDate;
                           });





            });


            var main_info ='<h1>' + evt.name + '</h1>';
            main_info += '<p>' +  evt.templateInfo.title + '</p>';
            main_info += '<p>' + evt.description + '</p>';
            main_info += '<p> Date: ' + dateString + " "+ timeOfEvent+ '</p>';
            main_info += '<button class="eventsButton">View Event Details</button>';


            // only counts first record
            // main_info += '<p class="mainInfo">' + locations.city + ','+ locations.state +'</p>';



            var secondary_info = '<h1 class="">' + 'hello'+ '</h1>';
            secondary_info += '<p class="">' + evt.description + '</p>';
            secondary_info += '<p class="">' + evt.createdDate + '</p>';
            secondary_info += '<p class="">' + evt.createdDate + '</p>';
            secondary_info += '<p class="">' + evt.guestsCanInviteOthers + '</p>';
                $("div.content").append("<div class=event><div class=main_info>"+ main_info +"<div class='secondary_info>'"+ secondary_info +"<input class=attending type=checkbox>"+"I will attend this event"+"</>"+"</div></div></div>");


        });

    }

    console.log("done");

});
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
0

just declare it out of function and you are able to use that variable in your main_info and secondary_info i.e.:

var city;
var state;
var timeZone;
var contactPhone;
var contactEmail;
var contactName;
var address1;
var address2;
var postalCode;

//hosts
var host;
var specialGuest;
var cohost;


//tiers
var tierTitle;
var tierDecription;
var tierPrice;
var tierRaiser;
var tierMax;
var tierQuantity;

var shiftStart;
var shiftEnd;       //getting all nested records


evt.locations.forEach(function(locations, i, array) {
    //location data
    city= evt.locations[i].city;
    state= evt.locations[i].state;
    timeZone= evt.locations[i].timezone;
    contactPhone= evt.locations[i].contactPhone;
    contactEmail= evt.locations[i].contactEmail;
    contactName= evt.locations[i].contactName;
    address1= evt.locations[i].address1;
    address2= evt.locations[i].address2;
    postalCode= evt.locations[i].postalCode;

    //hosts
    host= evt.locations[i].tags.host;
    specialGuest=evt.locations[i].tags.specialGuest;
    cohost=evt.locations[i].tags.cohost;


    //tiers
    tierTitle= evt.locations[i].tiers[i].title;
    tierDecription= evt.locations[i].tiers[i].decription;
    tierPrice=evt.locations[i].tiers[i].price;
    tierRaiser=evt.locations[i].tiers[i].raiser;
    tierMax=evt.locations[i].tiers[i].maxNum;
    tierQuantity=evt.locations[i].tiers[i].quantity;

    shiftStart= evt.locations[i].shifts[i].startDate;
    shiftEnd= evt.locations[i].shifts[i].endDate;

    console.log(evt.locations[i].city)

});
Ajay Makwana
  • 2,330
  • 1
  • 17
  • 32