Extracting data form another section with same ID (Appcelerator) - javascript

I have the following JSON: (its simplified a bit for you)
{ returnJSON = {
studentDataVOs = {
finalGrades = (
{
grade = A;
percent = 100;
sectionid = 7744;
reportingTermId = 801;
},
{
grade = B+;
percent = 89;
sectionid = 7745;
reportingTermID = 801;
});
reportingTerms = (
{
id = 801;
title = S1;
},
{
id = 802;
title = S2;
});
sections = (
{
id = 7744;
termID = 801;
courseTitle = Physics;
courseCode = 88A;
},
{
id = 7745;
termID = 801;
courseTitle = Government;
courseCode = 90B;
});
};
};
}
I am building an app using Appcelerator Titanium that displays a table view with the data hopefully showing the following:
Physics (88A) - S1 (Grade: A, 100%)
Government (90B) - S1 (Grade: B+, 89%)
...and so on...
I have the table view set up and the following code extracts the data from the sections and puts it in the labels of the table view:
var response = JSON.parse(response);
var sections = response.returnJSON.studentDataVOs.sections;
for (i=0;i<sections.length;i++) {
var courseName = sections[i].courseTitle;
var courseCode = sections[i].courseCode;
}
What I cannot figure out is how to go about fetching the grade, and term title for each individual class. As you can see, the data for each section contains an ID and termID, which direct me to a section in the finalGrades and reportingTerms that contains the ID or termID, where I need to fetch the final grades, percents, and term titles.
Can anyone help me with this? I have been trying on and off for two days trying to figure this out...

You should create indexes for each field you've listed. It's pretty simple:
//for example you have user list
var users = [{
id : 1, email : 'user#gmail.com',
nickname : 'John'
}, {
id : 2, email : 'user#stackoverflow.com',
nickname : 'Peter'
}];
//and you need to query user by his email, id and nickname
//first, create 3 index list
var usersIdIndex = {}, usersEmailIndex = {},
usersNicknameIndex = {};
//then fill them
users.forEach(function(user){
usersIdIndex[user.id] = user;
usersEmailIndex[user.email] = user;
usersNicknameIndex[user.nickname] = user;
});
//now you can get users by any of this fields
//for example
console.log(usersIdIndex[2].nickname== 'Peter');
console.log(usersNicknameIndex['John'].email == 'user#gmail.com');

Sections -> Final Grades
In the sections list, I would pass a variable in the tablerow that I could use to query for the next set of data. You need the section id to associate the data with the data in the final grade, so I would add it to my table row.
When creating your table:
// This loop to loop through the data.
function getSections(_args){
var response = JSON.parse(response);
var sections = response.returnJSON.studentDataVOs.sections;
for (i=0;i<sections.length;i++) {
createMyRow({
courseName: sections[i].courseTitle,
courseCode: sections[i].courseCode,
sectionId: sections[i].id
});
}
}
// This function creates the rows for the table
function createMyRow(_args){
// the sectionId is now included in the tableRow and can be used later for your
// next query.
// allows the sectionId value is now can be queried when a user clicks it
// through e.rowData.
var tableRow = Ti.UI.createTableViewRow({
sectionId: _args.sectionId
});
var title = Ti.UI.createLabel({
text: _args.courseName
});
tableRow.add(title);
return tableRow;
}
var tableView = Ti.UI.createTableView();
var data = [];
function refreshTable()
data = getSections();
var rows = [];
for( var i = 0; i<data.length; i++){
rows.push(createMyRow(data[i]);
}
tableView.setData(rows);
}
// this passes the value of the sectionId so you can use it to look up your next section.
tableView.addEventListener('click', function(e){
getFinalGrades({
sectionId: e.rowData.sectionId
})
});
function getFinalGrades(_args){
var finalGrades = response.returnJSON.studentDataVOs.finalGrades
var data = [];
for (i=0;i<finalGrades.length;i++) {
if(finalGrades[i].sectionId == _args.sectionId){
data.push({
grade: finalGrades[i].grade,
percent: finalGrades[i].percent
});
}
}
return data;
}
I hacked this together rather quickly looking at some of my code examples. At the end of the getFinalGrades function, you would have an array of finalGrades that were only from sectionId you clicked.

Related

How to compare a value with each item of range

for the last 3 days (my first 3 days of coding) i've been trying to code an script to get my google contacts that have certain keyword, it being "Catamarca", on their name and also to delete that keyword after they've been added to the spreadsheet leaving only their name.
I've been succesfull in all of this. But now i want to only run the script on an existing database, and only run it if the new contacts are not on the sheet already, and not write over the existing ones.
Here is my code so far:
function impContacts() {
// variables
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GContacts");
var grupo = ContactsApp.getContactGroupById("http://www.google.com/m8/feeds/groups/email#gmail.com/base/6")
const contactos = grupo.getContacts();
const arraycontacts = [];
// get the last row on B with data on it
const lastRow = sheet.getLastRow();
const Avals = sheet.getRange("B2:B" + lastRow).getValues();
const Alast = lastRow - Avals.reverse().findIndex(c => c[0] != '');
Logger.log(Alast);
var rangeInteres = sheet.getRange(2, 1, Alast, sheet.getLastColumn()).getValues();
// look for contacts that has in their name the word "Catamarca", and save them with their id, name and phone.
contactos.forEach(contacto => {
var phone = ""
if (contacto.getPhones()[0]) {
phone = contacto.getPhones()[0].getPhoneNumber()
};
var name = ""
if (contacto.getFullName().match("Catamarca")){
name = contacto.getFullName();
};
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
const datoscont = [idcont, name, phone];
arraycontacts.push(datoscont);
})
// save new contact
sheet.getRange(2, 1, arraycontacts.length, 3).setValues(arraycontacts);
// look for "catamarca"
range = sheet.getRange("B2:B")
var textFind = range.createTextFinder("Catamarca");
textFind.matchEntireCell(false);
textFind.ignoreDiacritics(true);
textFind.matchCase(false);
var textFound = textFind.findNext();
// Si encuentra coincidencia reemplazar por ""
if (textFound !== null) {
var vals = textFound.getValues();
textFind.replaceAllWith("");
}
}
What i need to keep the most is the ID of the existing contacts (the IDs are different from the ones coming from google contacts but the names are the same), because they are linked to an app created using AppSheet.
I believe there should be a way to accomplish this by editing this part of the code
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
In my head and with my current knowledge, the code should be working, but it's not, I mean, it runs, but overwrites everything.

How can I script a Google Form from a Spreadsheet to go to a specific page based on an answer?

I have successfully created a Google form that populates from a spreadsheet using code adapted from here: https://www.youtube.com/watch?v=BYA4URuWw0s . Now I would like to make the form go to a specific question based on the answer of a previous question without losing the function of updating from the spreadsheet. I have tried to alter code from here: How to assign Go_To_Page in Form Service on Multiple Choice? , but have yet to have any luck. Below is what I have as of now. I am very new to coding and any help will be greatly appreciated. Thanks in advance!!!
//insert your form ID
var FORM_ID = '1iA8jX720Eqi_GKwiA1RJiWwzt3vJ8XOOAqh-SjO9mXM';
//insert your sheet name with a list
var EMP_SHEET_NAME = 'empROSTER';
//insert your range of lis
//insert list id (before run getItemsOfForm function and look at t as A1Notation
var range1 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM_ID = '1097376824';
/*
add date question? -
form.addDateItem()
.setTitle('Date of Work Performed')
*/
//insert your sheet name with a list
var JOB_SHEET_NAME = 'jobROSTER';
//insert your range of list as A1Notation
var range2 = 'C2:C';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM2_ID = '773657499';
//insert your sheet name with a list
var AT_SHEET_NAME = '300';
//insert your range of list as A1Notation
var range3 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM3_ID = '1884670833';
//insert your sheet name with a list
var DT_SHEET_NAME = '1000';
//insert your range of list as A1Notation
var range4 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM4_ID = '379969286';
//insert your sheet name with a list
var CT_SHEET_NAME = '2000';
//insert your range of list as A1Notation
var range5 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM5_ID = '128282987';
//insert your sheet name with a list
var HOURS_SHEET_NAME = 'hourROSTER';
//insert your range of list as A1Notation
var range6 = 'B2:B';
//insert list id (before run getItemsOfForm function and look at log CTRL+Enter)
var ITEM6_ID = '1385334889';
//Section in question
function createGoTo(){
var af = FormApp.openById(FORM_ID);
var pAdmin = af.getItemById(AT_SHEET_NAME); //use findPageIds to get the page id of a pre-created page
var pDesign = af.getItemById(DT_SHEET_NAME);
var pCon = af.getItemById(CT_SHEET_NAME);
var item = ITEM2_ID
//create choices as an array
var choices = [];
choices.push(item.createChoice('Administration Job', pAdmin));
choices.push(item.createChoice('Design Job', pDesign));
choices.push(item.createChoice('Construction Job', pCon));
// assignes the choices for the question
item.setChoices(choices);
}
function findPageIds(){
var af = FormApp.getActiveForm();
var pages = af.getItems(FormApp.ItemType.PAGE_BREAK);
for (i in pages){
var pName = pages[i].getTitle();
var pId = pages[i].getId();
Logger.log(pName+":"+pId);
}
}
//End of section in question
function updateEmpName() {
var values_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(EMP_SHEET_NAME).getRange(range1).getValues();
values_[0][0] = values_[0][0].toString();
for(var i = 1; i < values_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values_[i][0] != "") {
values_[0].push(values_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM_ID);
list.asListItem().setChoiceValues(values_[0]);
}
function updateJobName() {
var values2_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(JOB_SHEET_NAME).getRange(range2).getValues();
values2_[0][0] = values2_[0][0].toString();
for(var i = 1; i < values2_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values2_[i][0] != "") {
values2_[0].push(values2_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM2_ID);
list.asListItem().setChoiceValues(values2_[0]);
}
function updateAdminTasks() {
var values3_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(AT_SHEET_NAME).getRange(range3).getValues();
values3_[0][0] = values3_[0][0].toString();
for(var i = 1; i < values3_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values3_[i][0] != "") {
values3_[0].push(values3_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM3_ID);
list.asListItem().setChoiceValues(values3_[0]);
}
function updateDesignTasks() {
var values4_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(DT_SHEET_NAME).getRange(range4).getValues();
values4_[0][0] = values4_[0][0].toString();
for(var i = 1; i < values4_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values4_[i][0] != "") {
values4_[0].push(values4_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM4_ID);
list.asListItem().setChoiceValues(values4_[0]);
}
function updateConstructionTasks() {
var values5_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(CT_SHEET_NAME).getRange(range5).getValues();
values5_[0][0] = values5_[0][0].toString();
for(var i = 1; i < values5_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values5_[i][0] != "") {
values5_[0].push(values5_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM5_ID);
list.asListItem().setChoiceValues(values5_[0]);
}
function updateHours() {
var values6_ = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(HOURS_SHEET_NAME).getRange(range6).getValues();
values6_[0][0] = values6_[0][0].toString();
for(var i = 1; i < values6_.length; i++){
// the if-block from https://productforums.google.com/d/msg/docs/v8ejYFpoGa8/HVqg6auIAg0J
if(values6_[i][0] != "") {
values6_[0].push(values6_[i][0].toString())
}
}
var form = FormApp.openById(FORM_ID);
var list = form.getItemById(ITEM6_ID);
list.asListItem().setChoiceValues(values6_[0]);
}
function getItemsOfForm(){
var form = FormApp.openById(FORM_ID);
var items = form.getItems(FormApp.ItemType.LIST);
for(var i in items){
Logger.log('id: ' + items[i].getId() + ' title: ' + items[i].getTitle());
}
}
PageBreakItem
A layout item that marks the start of a page. Items can be accessed or created from a Form.
PageNavigationType
An enum representing the supported types of page navigation. Page navigation types can be accessed from FormApp.PageNavigationType.
The page navigation occurs after the respondent completes a page that contains the option, and only if the respondent chose that option. If the respondent chose multiple options with page-navigation instructions on the same page, only the last navigation option has any effect. Page navigation also has no effect on the last page of a form.
Choices that use page navigation cannot be combined in the same item with choices that do not use page navigation.
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
var pageBreak = form.addPageBreakItem();
// Set some choices with go-to-page logic.
var rightChoice = item.createChoice('Vanilla', FormApp.PageNavigationType.SUBMIT);
var wrongChoice = item.createChoice('Chocolate', FormApp.PageNavigationType.RESTART);
// For GO_TO_PAGE, just pass in the page break item. For CONTINUE (normally the default), pass in
// CONTINUE explicitly because page navigation cannot be mixed with non-navigation choices.
var iffyChoice = item.createChoice('Peanut', pageBreak);
var otherChoice = item.createChoice('Strawberry', FormApp.PageNavigationType.CONTINUE);
item.setChoices([rightChoice, wrongChoice, iffyChoice, otherChoice]);
You can follow the sample create by Google and the implementation used in
Mogsdad's answert to further understand the flow.
I've added his code snippet:
function createForm() {
// Create a form and add a new multiple-choice item and a page-break item.
var form = FormApp.create('Form Name');
var item = form.addMultipleChoiceItem();
item.setTitle('Do you like Food')
var page2 = form.addPageBreakItem()
.setTitle('Page 2')
var item2 = form.addTextItem();
item2.setTitle('Why do you like food?')
var page3 = form.addPageBreakItem()
.setTitle('Page 3')
var item3 = form.addTextItem();
item3.setTitle("Why don't you like food?")
item.setTitle('Question')
.setChoices([
item.createChoice('Yes',page2),
item.createChoice('No',page3)
]);
}

C# class only returning first item of a JavaScript array - cant update just one record of db

I have a grid in html with some data of example Directors. Then I change the data, and want to update db.
Using a JS function, I get all the details from the grid, and save it in an array.
function getDirectorGridDetails() {
var tableRows = document.getElementById("tc_directorsGrid_table").rows
for (var i = 0; i < tableRows.length; i++) {
var directorRow = tableRows[i]
if (directorRow) {
var directorRowSeq = directorRow.getAttribute("data-id");
var directorDetailDesc = directorRow.getElementsByTagName("td")[0].innerHTML;
var directorDetailGender = directorRow.getElementsByTagName("td")[1].innerHTML;
var directorDetailDateApp = directorRow.getElementsByTagName("td")[2].innerHTML;
var directorDetailDateRes = directorRow.getElementsByTagName("td")[3].innerHTML;
if (!x) {
var x = [];
var Seq = [];
var Description = [];
var Gender = [];
var DateAppointed = [];
var DateResigned = [];
}
Seq.push(directorRowSeq);
Description.push(directorDetailDesc);
Gender.push(directorDetailGender);
DateAppointed.push(directorDetailDateApp);
DateResigned.push(directorDetailDateRes);
}
else {
break;
}
}
var directorsclass = {
"directorsclass": {
"Seq": Seq,
"Description": Description,
"Gender": Gender,
"DateAppointed": DateAppointed,
"DateResigned": DateResigned
}
}
return directorsclass
};
then, when I enter my C# side, to get the details and update db, the class is only returning the first items of the array.
Is there a way of getting each object from array, pass that in to class?
c# code snippit
[HttpPost]
[Route("client/updateDirector")]
public ActionResult updateDirector([System.Web.Http.FromBody] DirectorsClass directorsclass)
{}
when it get to directorsclass, it only shows first element

returning nested json values using loop (google spreadsheet)

I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});

Dynamically expanding table from object array

As the title states, I'm trying to create a table that will dynamically expand or shrink depending on the number of objects in the array. Each of these objects has 10 properties which all need to be displayed in separate rows. I started writing the for loop to iterate over the array and display each property using JQuery's .html() and realized it would look messy when all said and done, but I do not know where to start.. The complete code is below, but I'm working in the showResults function now..
//scripts
//Customer Object constructor
function CustomerObject(fName, lName, mName, address, city, state, zip, age, gender, pizza) {
this.fName = fName;
this.lName = lName;
this.mName = mName;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.age = age;
this.gender = gender;
this.pizza = pizza;
}
//Array of CustomerObjest
var CustomerArray = new Array();
$(document).ready(function () {
$("#TBFName").focus();
});
$("#BtnSave").click(function () {
//When Save button is pressed.
Validate();
});
$("#BtnReset").click(function () {
//When Clear button is pressed
ClearAllInfo();
});
$("#BtnDone").click(function () {
//When Done button is pressed
ShowResults();
});
$("#BtnMore").click(function () {
//When Enter More button is pressed
ShowResults();
$("#DivFormContainer").show();
$("#DivResults").hide();
});
$("#BtnMoreClearCustomers").click(function () {
//When Clear All Customers button is pressed
CustomerArray = new Array();
$("#DivFormContainer").show();
$("#DivResults").hide();
});
function Validate() {
var isValid = true;
var fstName = $("#TBFName").val();
var mdlName = $("#TBMI").val();
var lstName = $("#TBLName").val();
var addrs = $("#TBAdress").val();
var cit = $("#TBCity").val();
var stat = $("#DDState").val();
var zipCode = $("#TBZip").val();
var gend = $("input:radio[name='RGGender']:checked").val();
var old = $("#TBAge").val();
var pza = $("input:radio[name='RGLikePizza']:checked").val();
// Validation goes Here for All Fields
if (isValid == true) { //If isValid is still true, no errors
CustomerArray.push(new CustomerObject(fstName, lstName, mdlName, addrs, cit, stat, zipCode, old, gend, pza));
$("#DivMessage").show();
$("#DivMessage").html("Record Saved. Add a new record or press done to see results.");
$("#DivMessage").fadeOut(1600);
}
}
function ShowResults() {
ClearAllInfo();
$("#DivResults").show();
$("#DivFormContainer").hide();
//Code to display all customers information
for (var i = 0; i < CustomerArray.length; i++) {
$("#list").html(CustomerArray[i].fName + CustomerArray[i].lName + CustomerArray[i].mName);
//create table?
}
}
function ClearResultsDiv() {
$("#DivResults").html("");
}
function ClearAllInfo() {
$("input[type=text]").val("");
$("textarea").val("");
$("select").prop('selectedIndex', 0);
$(".error").html("");
$("input[type=radio]").attr('checked', false);
}
This is where direct DOM manipulation becomes messy and you are better off using an MVC framework. There are many to choose from: http://todomvc.com
I made a quick example using AngularJS:
http://codepen.io/anon/pen/nuGwz?editors=101
The nice thing is, you then only need to care about modifying your data (the customer array). The view (DOM) gets updated automatically. Like so:
$scope.CustomerArray.push({name: 'Joanna', age: '46', city: 'New York'});
As I understand it, you want to generate a table from an array containing row data.
Here's one way to make a table:
var maketable = (function(){
var elem, td, th, tr;
elem = function(elemtype, children){
var el = document.createElement(elemtype);
children.forEach(function(child){
el.appendChild(child);
});
return el;
};
td = function(s){
return elem('td', [document.createTextNode(s)]);
};
th = function(s){
return elem('th', [document.createTextNode(s)]);
};
tr = function(row){
return elem('tr', row.map(td));
};
return function(data){
var cols, rows, thead, tbody, table;
cols = Object.keys(data[0]);
rows = data.map(function(row){
return Object.keys(data[0]).map(function(key){
return row[key];
});
});
thead = elem('thead', [elem('tr', cols.map(th))]);
tbody = elem('tbody', rows.map(tr));
table = elem('table', [thead, tbody]);
return table;
};
}());
Example usage:
var data = [{a: 'a0', b: 'b0'}, {a: 'a1', b: 'b1'}, {a: 'a2', b: 'b2'}];
var table = maketable(data);
document.body.appendChild(table);

Categories