watts
watts

Reputation: 95

Returning a JSON object from a Javascript function

Trying to parse through some livestream JSON data and see if an event has a specific tag. If it doesn't then I'll use that data to output values, etc.

For whatever reason, upcoming_event isn't being assigned the event object (which is the return value of the findPublicEvent function.

The console.log of the event object works fine - but returning it doesn't work :/

// get our NLC data from livestream.
// -> note: need the '?callback=?' to convert to JSONP for cross-domain usage
var $uri = 'http://api.new.livestream.com/accounts/newlifechurchtv/?callback=?';
$.getJSON($uri, function(data) {
    parseNLCData(data);
});

parseNLCData = function(nlc_data){
  // set our variable to the return first event
  // nlc_data.upcoming_events.data is a json array of events
  window.upcoming_event = findPublicEvent(nlc_data.upcoming_events.data);
}

// should return single public event
function findPublicEvent (all_events) {
  // if we have events
  if (all_events) {
    // loop through events to find public event
    $.each(all_events, function(index,value){
      // get all the tags, remove whitespace, and put into array
      var $tags = value.tags.replace(/ /g, '').toLowerCase().split(',');
      // check for privacy.
      var $privacy = $.inArray('private', $tags);
      if ($privacy === -1) {
        // if the event isn't private -> return it!
        console.log(value);
        return value;
      }
    });
   // otherwise .... ->
   } else {
    // we don't have events, sooo, no dice.
    return false;
   }

 };

Upvotes: 0

Views: 220

Answers (1)

Quentin
Quentin

Reputation: 943615

findPublicEvent isn't returning it. The anonymous function you pass to each is returning it.

Since it is the return value of findPublicEvent that you are capturing, you can't see it.

  1. Define a variable in the scope of findPublicEvent
  2. Assign a value to it from inside your anonymous function (using a regular assignment, not a return)
  3. Return that variable from findPublicEvent

Upvotes: 3

Related Questions