Я пытаюсь получить доступ ко всем моим данным, чтобы я мог добавить его в свой HTML-документ.

Я не смог достать ни один из вложенных массивов с помощью evt.locations[i].foo, потому что он вернул бы только первую запись.

Моя цель - получить доступ к переменным, которые я объявил, и добавить их в main_info или secondary_info.

Примечание: я, очевидно, буду реструктурировать количество абзацев, используемых каждый раз, но это просто, чтобы увидеть его на странице.

$.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>';

код в JsBin

0
ImJessW 18 Дек 2015 в 11:50

3 ответа

Лучший ответ

У вас уже есть готовый к использованию объект из http-вызова, зачем анализировать его снова

$(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>
2
Vanojx1 18 Дек 2015 в 10:17

Просто объявите его вне функции, и вы сможете использовать эту переменную в своих main_info и secondary_info т.е.

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)

});
0
Ajay Makwana 18 Дек 2015 в 10:11

Пытаться:

$(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");

});
0
madalinivascu 18 Дек 2015 в 09:48