-
Notifications
You must be signed in to change notification settings - Fork 56
/
getData.js
94 lines (72 loc) · 2.62 KB
/
getData.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
var _ = require('underscore');
var Tabletop = require('tabletop');
module.exports =
function(callback) {
var sheetUrl = 'https://docs.google.com/spreadsheets/d/1UTmofeY8rPZvXdN_CNJXfFgPlexiMmlSs5W8oPhqFko/pubhtml';
var Sheet = {};
// =====
// Handle the data
// =====
function onLoad(data, tabletop) {
console.log( 'Found ' + tabletop.foundSheetNames );
// An array of sheets found
// => ['sheet-name','Other Sheet','that's a sheet']
var sheets = tabletop.foundSheetNames;
// For each sheet, generate a collection jekyll can use
_.each(sheets, function(sheet){
// Get the objects (rows) in the sheet
var objects;
objects = tabletop.sheets(sheet).all();
// Get an array of the column headers from the sheet, in the correct order
// We do this because JS doesn't necessary require entries in an object to be read in order
// We'll use this below to create a unique ID from the first column, if needed
var columns;
columns = tabletop.sheets(sheet).column_names;
// For each object, make sure we have a unique id. If not, make one.
_.each(objects, function(object){
// If the 'unique-id' key doesn't exist, create a unique id from the first column key/value
if (!object['unique-id']) {
object = createUniqueId(object,columns);
}
}); // end each objects
// Insert our sheet and its objects (rows) into the Sheet object
Sheet[sheet] = objects;
}); // end each sheets
Sheet['created'] = new Date();
callback(null,Sheet);
};
// =====
// Create a unique key/value for an object from the first item
// =====
function createUniqueId(object,columns) {
// Get the first column, in order from the Google Sheet
column = _.first(columns);
// Get the value for that column key
var value;
value = object[column];
// Remove non-alphanumeric characters, except for spaces
value = value.replace(/[^\w\s]/gi, '')
// Replace spaces with dashes, lowercase the string
value = value.split(' ').join('-').toLowerCase();
// Create a new key/value pair to put into the object
var newPair = {};
newPair =
{
'unique-id' : value
};
// Return the object with the new columnId
return _.extend(object, newPair);
}
// =====
// Tabletop options
// =====
var options = {
key: sheetUrl,
callback: onLoad,
simpleSheet: true
};
// =====
// Do the thing
// =====
Tabletop.init(options);
}