简体   繁体   中英

How to Parse Facebook Graph API “hours” response

I'm working with Facebook Graph API to get some data from a facebook page but I don't know how to handle the result in "hours" which is something like this:

{
    "wed_1_open": "17:00", 
    "wed_1_close": "02:00", 
    "thu_1_open": "17:00", 
    "thu_1_close": "02:00", 
    "fri_1_open": "17:00", 
    "fri_1_close": "02:00", 
    "sat_1_open": "12:00", 
    "sat_1_close": "02:00", 
    "sun_1_open": "12:00", 
    "sun_1_close": "20:00"
  }

So I wonder how to parse this result to get some human-readable text like the one in the info tab:

wed - fri: 17:00 - 2:00
sat: 12:00 - 2:00
sun: 12:00 - 20:00

Thank in advance!!

Here's one way to do this: http://jsbin.com/xavaxudi/1/edit?js,console .

Note: this is something I just wrote up in a few minutes. If you're dealing with large quantities of data then you'll probably have to optimize accordingly.

var rawFbData = {
    "wed_1_open": "17:00", 
    "wed_1_close": "02:00", 
    "thu_1_open": "17:00", 
    "thu_1_close": "02:00", 
    "fri_1_open": "17:00", 
    "fri_1_close": "02:00", 
    "sat_1_open": "12:00", 
    "sat_1_close": "02:00", 
    "sun_1_open": "12:00", 
    "sun_1_close": "20:00"
  };

console.log(rawFbData);

var formattedData = {};
for (var key in rawFbData) {
  if (key.substr(-5) === '_open') {
    var openDay = key.substr(0, 3);
    var openTime = rawFbData[key];

    var endTimeKey = key.replace('_open', '_close');
    var endTime = rawFbData[endTimeKey];

    var formattedDataKey = openTime + ' - ' + endTime;

    if (formattedData[formattedDataKey] === undefined) {
     formattedData[formattedDataKey] = []; 
    }

    formattedData[formattedDataKey].push(openDay);
  }  
}

//console.log(formattedData);

for (var formattedDatakey in formattedData) {
  var formattedDatakeyLen = formattedData[formattedDatakey].length;

  if (formattedDatakeyLen > 1) {
    var firstDay = formattedData[formattedDatakey][0];
    var lastDay = formattedData[formattedDatakey][formattedDatakeyLen - 1];

    console.log(firstDay + ' - ' + lastDay + ': ' + formattedDatakey);
  }
  else if (formattedData[formattedDatakey].length === 1) {
    console.log(formattedData[formattedDatakey][0] + ': ' + formattedDatakey);
  }
}

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