Tables to JSON -> Adding additional object identifiers from <tr> ids - javascript

I am using tableToJson, which you may or may not be familiar with, to convert a table to JSON (Ive included the code for it here if you don't know it). Simple enough. The output is entirely as expected and looks like:
{"data":[
{"Time":"6:30am - 8:30am","Monday":"","Tuesday":"Maths","Wednesday":"","Thursday":"","Friday":""},
{"Time":"11:15am - 12:45pm","Monday":"Maths","Tuesday":"","Wednesday":"English","Thursday":"","Friday":""},
{"Time":"3:00pm - 5:00pm","Monday":"","Tuesday":"","Wednesday":"English","Thursday":"","Friday":""},
{"Time":"5:00pm - 7:00pm","Monday":"","Tuesday":"Science","Wednesday":"","Thursday":"","Friday":""},
{"Time":"7:00pm - 9:00pm","Monday":"","Tuesday":"Science","Wednesday":"","Thursday":"","Friday":""}]
}
However, I need to expand on it to take the #ids of each <tr> so the JSON looks like: (Assuming the table HTML is <tr id="session 1"></tr> etc.)
{
"data":{
"session 1":{"Time":"6:30am - 8:30am","Monday":"","Tuesday":"sdfsdf","Wednesday":"","Thursday":"","Friday":""},
"session 2":{"Time":"11:15am - 12:45pm","Monday":"sdfsdfsdf","Tuesday":"","Wednesday":"","Thursday":"","Friday":""},
"session 3":{"Time":"3:00pm - 5:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""},
"session 4":{"Time":"5:00pm - 7:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""},
"session 5":{"Time":"7:00pm - 9:00pm","Monday":"","Tuesday":"","Wednesday":"","Thursday":"","Friday":""}
}
}
For reference The code for tableToJson looks like:
(function( $ ) {
'use strict';
$.fn.tableToJSON = function(opts) {
// Set options
var defaults = {
ignoreColumns: [],
onlyColumns: null,
ignoreHiddenRows: true,
ignoreEmptyRows: false,
headings: null,
allowHTML: false,
includeRowId: false,
textDataOverride: 'data-override',
textExtractor: null
};
opts = $.extend(defaults, opts);
var notNull = function(value) {
return value !== undefined && value !== null;
};
var ignoredColumn = function(index) {
if( notNull(opts.onlyColumns) ) {
return $.inArray(index, opts.onlyColumns) === -1;
}
return $.inArray(index, opts.ignoreColumns) !== -1;
};
var arraysToHash = function(keys, values) {
var result = {},index=0, name = 'test';
$.each(values, function(i, value) {
// when ignoring columns, the header option still starts
// with the first defined column
if ( index < keys.length && notNull(value) ) {
result[ keys[index] ] = value;
index++;
}
});
return result;
};
var cellValues = function(cellIndex, cell, isHeader) {
var $cell = $(cell),
// textExtractor
extractor = opts.textExtractor,
override = $cell.attr(opts.textDataOverride);
// don't use extractor for header cells
if ( extractor === null || isHeader ) {
return $.trim( override || ( opts.allowHTML ? $cell.html() : cell.textContent || $cell.text() ) || '' );
} else {
// overall extractor function
if ( $.isFunction(extractor) ) {
return $.trim( override || extractor(cellIndex, $cell) );
} else if ( typeof extractor === 'object' && $.isFunction( extractor[cellIndex] ) ) {
return $.trim( override || extractor[cellIndex](cellIndex, $cell) );
}
}
// fallback
return $.trim( override || ( opts.allowHTML ? $cell.html() : cell.textContent || $cell.text() ) || '' );
};
var rowValues = function(row, isHeader) {
var result = [];
var includeRowId = opts.includeRowId;
var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false;
var rowIdName = (typeof includeRowId === 'string') === true ? includeRowId : 'rowId';
if (useRowId) {
if (typeof $(row).attr('id') === 'undefined') {
result.push(rowIdName);
}
}
$(row).children('td,th').each(function(cellIndex, cell) {
result.push( cellValues(cellIndex, cell, isHeader) );
});
return result;
};
var getHeadings = function(table) {
var firstRow = table.find('tr:first').first();
return notNull(opts.headings) ? opts.headings : rowValues(firstRow, true);
};
var construct = function(table, headings) {
var i, j, len, len2, txt, $row, $cell,
tmpArray = [], cellIndex = 0, result = [];
table.children('tbody,*').children('tr').each(function(rowIndex, row) {
if( rowIndex > 0 || notNull(opts.headings) ) {
var includeRowId = opts.includeRowId;
var useRowId = (typeof includeRowId === 'boolean') ? includeRowId : (typeof includeRowId === 'string') ? true : false;
$row = $(row);
var isEmpty = ($row.find('td').length === $row.find('td:empty').length) ? true : false;
if( ( $row.is(':visible') || !opts.ignoreHiddenRows ) && ( !isEmpty || !opts.ignoreEmptyRows ) && ( !$row.data('ignore') || $row.data('ignore') === 'false' ) ) {
cellIndex = 0;
if (!tmpArray[rowIndex]) {
tmpArray[rowIndex] = [];
}
if (useRowId) {
cellIndex = cellIndex + 1;
if (typeof $row.attr('id') !== 'undefined') {
tmpArray[rowIndex].push($row.attr('id'));
} else {
tmpArray[rowIndex].push('');
}
}
$row.children().each(function(){
$cell = $(this);
// skip column if already defined
while (tmpArray[rowIndex][cellIndex]) { cellIndex++; }
// process rowspans
if ($cell.filter('[rowspan]').length) {
len = parseInt( $cell.attr('rowspan'), 10) - 1;
txt = cellValues(cellIndex, $cell);
for (i = 1; i <= len; i++) {
if (!tmpArray[rowIndex + i]) { tmpArray[rowIndex + i] = []; }
tmpArray[rowIndex + i][cellIndex] = txt;
}
}
// process colspans
if ($cell.filter('[colspan]').length) {
len = parseInt( $cell.attr('colspan'), 10) - 1;
txt = cellValues(cellIndex, $cell);
for (i = 1; i <= len; i++) {
// cell has both col and row spans
if ($cell.filter('[rowspan]').length) {
len2 = parseInt( $cell.attr('rowspan'), 10);
for (j = 0; j < len2; j++) {
tmpArray[rowIndex + j][cellIndex + i] = txt;
}
} else {
tmpArray[rowIndex][cellIndex + i] = txt;
}
}
}
txt = tmpArray[rowIndex][cellIndex] || cellValues(cellIndex, $cell);
if (notNull(txt)) {
tmpArray[rowIndex][cellIndex] = txt;
}
cellIndex++;
});
}
}
});
$.each(tmpArray, function( i, row ){
if (notNull(row)) {
// remove ignoredColumns / add onlyColumns
var newRow = notNull(opts.onlyColumns) || opts.ignoreColumns.length ?
$.grep(row, function(v, index){ return !ignoredColumn(index); }) : row,
// remove ignoredColumns / add onlyColumns if headings is not defined
newHeadings = notNull(opts.headings) ? headings :
$.grep(headings, function(v, index){ return !ignoredColumn(index); });
txt = arraysToHash(newHeadings, newRow);
result[result.length] = txt;
}
});
return result;
};
// Run
var headings = getHeadings(this);
return construct(this, headings);
};
})( jQuery );
I'm probably missing something really simple, but honestly cannot see how to do this. Any help would be super appreciated. Thank you all in advance!

Please rethink why you'd need to change it. This already provides valid ordered content in a JSON array (accessible via foo.data[0], foo.data[1] etc, or iterable with for(var i; i<foo.data.length;i++){}).
What you want will give you something with no guaranteed order (properties order in an object is irrelevant in JSON) and goes against the flow).
Edit: Stupid API.
If you must conform to some obscure and evil standard, edit the data after it was created. You can't expect $.fn.tableToJSON not to conform to JSON & javascript standards...
var foo = // output from $.fn.tableToJSON
var out = {data:{}}; //declare an *object* instead of an array
for(var i = 0; i < foo.data.length; i++){
out.data['Session ' + (i + 1)] = foo.data[i];
}
//debug output
console.log(JSON.stringify(out))

Related

How to restore a JSON string from a compressed blob in Google Apps Script?

I need to store a large json into a cell of a spreadsheet. Since there's a 50k character limit I thought of compressing the json string. I've managed to store the compressed blob as a base64 encoded string, but I'm failing to restore it to the original json. When the readLargeJson function is called I get the following error: "Blob object must have non-null content type for this operation".
The insertLargeJson function below seems to be working correctly.
I tried also storing without the base64 encoding, but didn't help.
function insertLargeJson()
{
var obj = {};
obj["dummy"] = [];
// Just to make the json huge
for (var i = 0; i < 10000; i++)
{
obj["dummy"].push("value");
}
var activeSheet = SpreadsheetApp.getActiveSheet();
var str = JSON.stringify(obj);
var blob = Utilities.newBlob(str, 'application/octet-stream');
var compressedBlob = Utilities.zip([blob]);
var encoded = Utilities.base64Encode(compressedBlob.getDataAsString());
activeSheet.getRange(1, 1).setValue(encoded);
}
function readLargeJson()
{
var activeSheet = SpreadsheetApp.getActiveSheet();
var values = activeSheet.getSheetValues(1, 1, 1, 1);
var value = values[0, 0];
var decoded = Utilities.base64Decode(value);
var blob = Utilities.newBlob(decoded);
var unzipped = Utilities.unzip(blob);
var obj = JSON.parse(unzipped.getDataAsString());
Browser.msgBox('Test Json array size', "" + obj["dummy"].length, Browser.Buttons.OK);
}
I don't necessarily need to use the blob interface to compress the json, any solution that would compress the json string and that would be storable in a cell for later retrieving the original json would work.
It is an interesting concept so I search a bit and get something working.
In your code you have to use compressedBlob.getBytes() to encode data and not compressedBlob.getDataAsString(). To create a blob in your read function you must use bytes in input.
Then in your read function the unzip return an array and before to get the data you have to use the getAs() function. So you must have unzipped[0].getAs('application/octet-stream').getDataAsString() and not unzipped.getDataAsString()
I made a single function to ease testing, so you just have to split it depending your need.
function insertReadLargeJson(){
var obj = {};
obj["dummy"] = [];
// Just to make the json huge
for (var i = 0; i < 10000; i++)
{
obj["dummy"].push("value");
}
// Logger.log(obj)
var activeSheet = SpreadsheetApp.getActiveSheet();
var str = JSON.stringify(obj);
var blob = Utilities.newBlob(str, 'application/octet-stream');
var compressedBlob = Utilities.zip([blob]);
var encoded = Utilities.base64Encode(compressedBlob.getBytes());
activeSheet.getRange(1, 1).setValue(encoded);
var decoded = Utilities.base64Decode(encoded);
var blob = Utilities.newBlob(decoded,'application/zip');
var unzipped = Utilities.unzip(blob);
var obj = JSON.parse(unzipped[0].getAs('application/octet-stream').getDataAsString());
// Logger.log(JSON.stringify(obj))
Logger.log(obj.dummy.length)
// Logger.log('Test Json array size', "" + obj["dummy"].length)
}
I was able to do it with the help of an external library.
I converted the code to be readable by Apps Script:
JSONPACK.gs
var TOKEN_TRUE = -1;
var TOKEN_FALSE = -2;
var TOKEN_NULL = -3;
var TOKEN_EMPTY_STRING = -4;
var TOKEN_UNDEFINED = -5;
function pack(json, options) {
// Canonizes the options
options = options || {};
// A shorthand for debugging
var verbose = options.verbose || false;
verbose && console.log('Normalize the JSON Object');
// JSON as Javascript Object (Not string representation)
json = typeof json === 'string' ? this.JSON.parse(json) : json;
verbose && console.log('Creating a empty dictionary');
// The dictionary
var dictionary = {
strings : [],
integers : [],
floats : []
};
verbose && console.log('Creating the AST');
// The AST
var ast = (function recursiveAstBuilder(item) {
verbose && console.log('Calling recursiveAstBuilder with ' + this.JSON.stringify(item));
// The type of the item
var type = typeof item;
// Case 7: The item is null
if (item === null) {
return {
type : 'null',
index : TOKEN_NULL
};
}
//add undefined
if (typeof item === 'undefined') {
return {
type : 'undefined',
index : TOKEN_UNDEFINED
};
}
// Case 1: The item is Array Object
if ( item instanceof Array) {
// Create a new sub-AST of type Array (#)
var ast = ['#'];
// Add each items
for (var i in item) {
if (!item.hasOwnProperty(i)) continue;
ast.push(recursiveAstBuilder(item[i]));
}
// And return
return ast;
}
// Case 2: The item is Object
if (type === 'object') {
// Create a new sub-AST of type Object ($)
var ast = ['$'];
// Add each items
for (var key in item) {
if (!item.hasOwnProperty(key))
continue;
ast.push(recursiveAstBuilder(key));
ast.push(recursiveAstBuilder(item[key]));
}
// And return
return ast;
}
// Case 3: The item empty string
if (item === '') {
return {
type : 'empty',
index : TOKEN_EMPTY_STRING
};
}
// Case 4: The item is String
if (type === 'string') {
// The index of that word in the dictionary
var index = indexOf.call(dictionary.strings, item);
// If not, add to the dictionary and actualize the index
if (index == -1) {
dictionary.strings.push(encode(item));
index = dictionary.strings.length - 1;
}
// Return the token
return {
type : 'strings',
index : index
};
}
// Case 5: The item is integer
if (type === 'number' && item % 1 === 0) {
// The index of that number in the dictionary
var index = indexOf.call(dictionary.integers, item);
// If not, add to the dictionary and actualize the index
if (index == -1) {
dictionary.integers.push(base10To36(item));
index = dictionary.integers.length - 1;
}
// Return the token
return {
type : 'integers',
index : index
};
}
// Case 6: The item is float
if (type === 'number') {
// The index of that number in the dictionary
var index = indexOf.call(dictionary.floats, item);
// If not, add to the dictionary and actualize the index
if (index == -1) {
// Float not use base 36
dictionary.floats.push(item);
index = dictionary.floats.length - 1;
}
// Return the token
return {
type : 'floats',
index : index
};
}
// Case 7: The item is boolean
if (type === 'boolean') {
return {
type : 'boolean',
index : item ? TOKEN_TRUE : TOKEN_FALSE
};
}
// Default
throw new Error('Unexpected argument of type ' + typeof (item));
})(json);
// A set of shorthands proxies for the length of the dictionaries
var stringLength = dictionary.strings.length;
var integerLength = dictionary.integers.length;
var floatLength = dictionary.floats.length;
verbose && console.log('Parsing the dictionary');
// Create a raw dictionary
var packed = dictionary.strings.join('|');
packed += '^' + dictionary.integers.join('|');
packed += '^' + dictionary.floats.join('|');
verbose && console.log('Parsing the structure');
// And add the structure
packed += '^' + (function recursiveParser(item) {
verbose && console.log('Calling a recursiveParser with ' + this.JSON.stringify(item));
// If the item is Array, then is a object of
// type [object Object] or [object Array]
if ( item instanceof Array) {
// The packed resulting
var packed = item.shift();
for (var i in item) {
if (!item.hasOwnProperty(i))
continue;
packed += recursiveParser(item[i]) + '|';
}
return (packed[packed.length - 1] === '|' ? packed.slice(0, -1) : packed) + ']';
}
// A shorthand proxies
var type = item.type, index = item.index;
if (type === 'strings') {
// Just return the base 36 of index
return base10To36(index);
}
if (type === 'integers') {
// Return a base 36 of index plus stringLength offset
return base10To36(stringLength + index);
}
if (type === 'floats') {
// Return a base 36 of index plus stringLength and integerLength offset
return base10To36(stringLength + integerLength + index);
}
if (type === 'boolean') {
return item.index;
}
if (type === 'null') {
return TOKEN_NULL;
}
if (type === 'undefined') {
return TOKEN_UNDEFINED;
}
if (type === 'empty') {
return TOKEN_EMPTY_STRING;
}
throw new TypeError('The item is alien!');
})(ast);
verbose && console.log('Ending parser');
// If debug, return a internal representation of dictionary and stuff
if (options.debug)
return {
dictionary : dictionary,
ast : ast,
packed : packed
};
return packed;
};
function unpack(packed, options) {
// Canonizes the options
options = options || {};
// A raw buffer
var rawBuffers = packed.split('^');
// Create a dictionary
options.verbose && console.log('Building dictionary');
var dictionary = [];
// Add the strings values
var buffer = rawBuffers[0];
if (buffer !== '') {
buffer = buffer.split('|');
options.verbose && console.log('Parse the strings dictionary');
for (var i=0, n=buffer.length; i<n; i++){
dictionary.push((buffer[i]));
}
}
// Add the integers values
buffer = rawBuffers[1];
if (buffer !== '') {
buffer = buffer.split('|');
options.verbose && console.log('Parse the integers dictionary');
for (var i=0, n=buffer.length; i<n; i++){
dictionary.push(base36To10(buffer[i]));
}
}
// Add the floats values
buffer = rawBuffers[2];
if (buffer !== '') {
buffer = buffer.split('|')
options.verbose && console.log('Parse the floats dictionary');
for (var i=0, n=buffer.length; i<n; i++){
dictionary.push(parseFloat(buffer[i]));
}
}
// Free memory
buffer = null;
options.verbose && console.log('Tokenizing the structure');
// Tokenizer the structure
var number36 = '';
var tokens = [];
var len=rawBuffers[3].length;
for (var i = 0; i < len; i++) {
var symbol = rawBuffers[3].charAt(i);
if (symbol === '|' || symbol === '$' || symbol === '#' || symbol === ']') {
if (number36) {
tokens.push(base36To10(number36));
number36 = '';
}
symbol !== '|' && tokens.push(symbol);
} else {
number36 += symbol;
}
}
// A shorthand proxy for tokens.length
var tokensLength = tokens.length;
// The index of the next token to read
var tokensIndex = 0;
options.verbose && console.log('Starting recursive parser');
return (function recursiveUnpackerParser() {
// Maybe '$' (object) or '#' (array)
var type = tokens[tokensIndex++];
options.verbose && console.log('Reading collection type ' + (type === '$' ? 'object' : 'Array'));
// Parse an array
if (type === '#') {
var node = [];
for (; tokensIndex < tokensLength; tokensIndex++) {
var value = tokens[tokensIndex];
options.verbose && console.log('Read ' + value + ' symbol');
if (value === ']')
return node;
if (value === '#' || value === '$') {
node.push(recursiveUnpackerParser());
} else {
switch(value) {
case TOKEN_TRUE:
node.push(true);
break;
case TOKEN_FALSE:
node.push(false);
break;
case TOKEN_NULL:
node.push(null);
break;
case TOKEN_UNDEFINED:
node.push(undefined);
break;
case TOKEN_EMPTY_STRING:
node.push('');
break;
default:
node.push(dictionary[value]);
}
}
}
options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
return node;
}
// Parse a object
if (type === '$') {
var node = {};
for (; tokensIndex < tokensLength; tokensIndex++) {
var key = tokens[tokensIndex];
if (key === ']')
return node;
if (key === TOKEN_EMPTY_STRING)
key = '';
else
key = dictionary[key];
var value = tokens[++tokensIndex];
if (value === '#' || value === '$') {
node[key] = recursiveUnpackerParser();
} else {
switch(value) {
case TOKEN_TRUE:
node[key] = true;
break;
case TOKEN_FALSE:
node[key] = false;
break;
case TOKEN_NULL:
node[key] = null;
break;
case TOKEN_UNDEFINED:
node[key] = undefined;
break;
case TOKEN_EMPTY_STRING:
node[key] = '';
break;
default:
node[key] = dictionary[value];
}
}
}
options.verbose && console.log('Parsed ' + this.JSON.stringify(node));
return node;
}
throw new TypeError('Bad token ' + type + ' isn\'t a type');
})();
}
function indexOfDictionary (dictionary, value) {
// The type of the value
var type = typeof value;
// If is boolean, return a boolean token
if (type === 'boolean')
return value ? TOKEN_TRUE : TOKEN_FALSE;
// If is null, return a... yes! the null token
if (value === null)
return TOKEN_NULL;
//add undefined
if (typeof value === 'undefined')
return TOKEN_UNDEFINED;
if (value === '') {
return TOKEN_EMPTY_STRING;
}
if (type === 'string') {
value = encode(value);
var index = indexOf.call(dictionary.strings, value);
if (index === -1) {
dictionary.strings.push(value);
index = dictionary.strings.length - 1;
}
}
// If has an invalid JSON type (example a function)
if (type !== 'string' && type !== 'number') {
throw new Error('The type is not a JSON type');
};
if (type === 'string') {// string
value = encode(value);
} else if (value % 1 === 0) {// integer
value = base10To36(value);
} else {// float
}
// If is number, "serialize" the value
value = type === 'number' ? base10To36(value) : encode(value);
// Retrieve the index of that value in the dictionary
var index = indexOf.call(dictionary[type], value);
// If that value is not in the dictionary
if (index === -1) {
// Push the value
dictionary[type].push(value);
// And return their index
index = dictionary[type].length - 1;
}
// If the type is a number, then add the '+' prefix character
// to differentiate that they is a number index. If not, then
// just return a 36-based representation of the index
return type === 'number' ? '+' + index : index;
};
function encode(str) {
if ( typeof str !== 'string')
return str;
return str.replace(/[\+ \|\^\%]/g, function(a) {
return ({
' ' : '+',
'+' : '%2B',
'|' : '%7C',
'^' : '%5E',
'%' : '%25'
})[a]
});
};
function decode(str) {
if ( typeof str !== 'string')
return str;
return str.replace(/\+|%2B|%7C|%5E|%25/g, function(a) {
return ({
'+' : ' ',
'%2B' : '+',
'%7C' : '|',
'%5E' : '^',
'%25' : '%'
})[a]
})
};
function base10To36(number) {
return Number.prototype.toString.call(number, 36).toUpperCase();
};
function base36To10(number) {
return parseInt(number, 36);
};
function indexOf(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
With that, your script can now be:
Code.gs
function insertLargeJson()
{
var obj = {};
obj["dummy"] = [];
// Just to make the json huge
for (var i = 0; i < 10000; i++)
{
obj["dummy"].push("value");
}
var activeSheet = SpreadsheetApp.getActiveSheet();
var packed = pack(obj);
var value = JSON.stringify(packed);
activeSheet.getRange(1, 1).setValue(value);
}
function readLargeJson()
{
var activeSheet = SpreadsheetApp.getActiveSheet();
var value = activeSheet.getRange(1,1).getValue();
var packed = JSON.parse(value);
var obj = unpack(packed);
Browser.msgBox('Test Json array size', "" + obj["dummy"].length, Browser.Buttons.OK);
}
Hope this helps!

xml2json - "X2JS is not defined"

I'm using xml2json for the first time to get an review feed to populate on a website and I keep getting errors such as;
Uncaught ReferenceError: X2JS is not defined
and
Uncaught TypeError: Cannot set property 'X2JS' of undefined
I can't seem to find a solution, this is the code;
jQuery(document).ready(function() {
//below here
//API Feed for Testimonials
(function (root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports === "object") {
module.exports = factory();
} else {
root.X2JS = factory();
}
}(this, function () {
return function (config) {
'use strict';
var VERSION = "1.2.0";
config = config || {};
initConfigDefaults();
initRequiredPolyfills();
function initConfigDefaults() {
if(config.escapeMode === undefined) {
config.escapeMode = true;
}
config.attributePrefix = config.attributePrefix || "_";
config.arrayAccessForm = config.arrayAccessForm || "none";
config.emptyNodeForm = config.emptyNodeForm || "text";
if(config.enableToStringFunc === undefined) {
config.enableToStringFunc = true;
}
config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
if(config.skipEmptyTextNodesForObj === undefined) {
config.skipEmptyTextNodesForObj = true;
}
if(config.stripWhitespaces === undefined) {
config.stripWhitespaces = true;
}
config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];
if(config.useDoubleQuotes === undefined) {
config.useDoubleQuotes = false;
}
config.xmlElementsFilter = config.xmlElementsFilter || [];
config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];
if(config.keepCData === undefined) {
config.keepCData = false;
}
}
var DOMNodeTypes = {
ELEMENT_NODE : 1,
TEXT_NODE : 3,
CDATA_SECTION_NODE : 4,
COMMENT_NODE : 8,
DOCUMENT_NODE : 9
};
function initRequiredPolyfills() {
}
function getNodeLocalName( node ) {
var nodeLocalName = node.localName;
if(nodeLocalName == null) // Yeah, this is IE!!
nodeLocalName = node.baseName;
if(nodeLocalName == null || nodeLocalName=="") // =="" is IE too
nodeLocalName = node.nodeName;
return nodeLocalName;
}
function getNodePrefix(node) {
return node.prefix;
}
function escapeXmlChars(str) {
if(typeof(str) == "string")
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '&apos;');
else
return str;
}
function unescapeXmlChars(str) {
return str.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/&apos;/g, "'").replace(/&/g, '&');
}
function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
var idx = 0;
for(; idx < stdFiltersArrayForm.length; idx++) {
var filterPath = stdFiltersArrayForm[idx];
if( typeof filterPath === "string" ) {
if(filterPath == path)
break;
}
else
if( filterPath instanceof RegExp) {
if(filterPath.test(path))
break;
}
else
if( typeof filterPath === "function") {
if(filterPath(obj, name, path))
break;
}
}
return idx!=stdFiltersArrayForm.length;
}
function toArrayAccessForm(obj, childName, path) {
switch(config.arrayAccessForm) {
case "property":
if(!(obj[childName] instanceof Array))
obj[childName+"_asArray"] = [obj[childName]];
else
obj[childName+"_asArray"] = obj[childName];
break;
/*case "none":
break;*/
}
if(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
if(checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
obj[childName] = [obj[childName]];
}
}
}
function fromXmlDateTime(prop) {
// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
// Improved to support full spec and optional parts
var bits = prop.split(/[-T:+Z]/g);
var d = new Date(bits[0], bits[1]-1, bits[2]);
var secondBits = bits[5].split("\.");
d.setHours(bits[3], bits[4], secondBits[0]);
if(secondBits.length>1)
d.setMilliseconds(secondBits[1]);
// Get supplied time zone offset in minutes
if(bits[6] && bits[7]) {
var offsetMinutes = bits[6] * 60 + Number(bits[7]);
var sign = /\d\d-\d\d:\d\d$/.test(prop)? '-' : '+';
// Apply the sign
offsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);
// Apply offset and local timezone
d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())
}
else
if(prop.indexOf("Z", prop.length - 1) !== -1) {
d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
}
// d is now a local time equivalent to the supplied time
return d;
}
function checkFromXmlDateTimePaths(value, childName, fullPath) {
if(config.datetimeAccessFormPaths.length > 0) {
var path = fullPath.split("\.#")[0];
if(checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
return fromXmlDateTime(value);
}
else
return value;
}
else
return value;
}
function checkXmlElementsFilter(obj, childType, childName, childPath) {
if( childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
}
else
return true;
}
function parseDOMChildren( node, path ) {
if(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
var result = new Object;
var nodeChildren = node.childNodes;
// Alternative for firstElementChild which is not supported in some environments
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx);
if(child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var childName = getNodeLocalName(child);
result[childName] = parseDOMChildren(child, childName);
}
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
var result = new Object;
result.__cnt=0;
var nodeChildren = node.childNodes;
// Children nodes
for(var cidx=0; cidx <nodeChildren.length; cidx++) {
var child = nodeChildren.item(cidx); // nodeChildren[cidx];
var childName = getNodeLocalName(child);
if(child.nodeType!= DOMNodeTypes.COMMENT_NODE) {
var childPath = path+"."+childName;
if (checkXmlElementsFilter(result,child.nodeType,childName,childPath)) {
result.__cnt++;
if(result[childName] == null) {
result[childName] = parseDOMChildren(child, childPath);
toArrayAccessForm(result, childName, childPath);
}
else {
if(result[childName] != null) {
if( !(result[childName] instanceof Array)) {
result[childName] = [result[childName]];
toArrayAccessForm(result, childName, childPath);
}
}
(result[childName])[result[childName].length] = parseDOMChildren(child, childPath);
}
}
}
}
// Attributes
for(var aidx=0; aidx <node.attributes.length; aidx++) {
var attr = node.attributes.item(aidx); // [aidx];
result.__cnt++;
result[config.attributePrefix+attr.name]=attr.value;
}
// Node namespace prefix
var nodePrefix = getNodePrefix(node);
if(nodePrefix!=null && nodePrefix!="") {
result.__cnt++;
result.__prefix=nodePrefix;
}
if(result["#text"]!=null) {
result.__text = result["#text"];
if(result.__text instanceof Array) {
result.__text = result.__text.join("\n");
}
//if(config.escapeMode)
// result.__text = unescapeXmlChars(result.__text);
if(config.stripWhitespaces)
result.__text = result.__text.trim();
delete result["#text"];
if(config.arrayAccessForm=="property")
delete result["#text_asArray"];
result.__text = checkFromXmlDateTimePaths(result.__text, childName, path+"."+childName);
}
if(result["#cdata-section"]!=null) {
result.__cdata = result["#cdata-section"];
delete result["#cdata-section"];
if(config.arrayAccessForm=="property")
delete result["#cdata-section_asArray"];
}
if( result.__cnt == 0 && config.emptyNodeForm=="text" ) {
result = '';
}
else
if( result.__cnt == 1 && result.__text!=null ) {
result = result.__text;
}
else
if( result.__cnt == 1 && result.__cdata!=null && !config.keepCData ) {
result = result.__cdata;
}
else
if ( result.__cnt > 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {
if( (config.stripWhitespaces && result.__text=="") || (result.__text.trim()=="")) {
delete result.__text;
}
}
delete result.__cnt;
if( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {
result.toString = function() {
return (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');
};
}
return result;
}
else
if(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
return node.nodeValue;
}
}
function startTag(jsonObj, element, attrList, closed) {
var resultStr = "<"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+":"):"") + element;
if(attrList!=null) {
for(var aidx = 0; aidx < attrList.length; aidx++) {
var attrName = attrList[aidx];
var attrVal = jsonObj[attrName];
if(config.escapeMode)
attrVal=escapeXmlChars(attrVal);
resultStr+=" "+attrName.substr(config.attributePrefix.length)+"=";
if(config.useDoubleQuotes)
resultStr+='"'+attrVal+'"';
else
resultStr+="'"+attrVal+"'";
}
}
if(!closed)
resultStr+=">";
else
resultStr+="/>";
return resultStr;
}
function endTag(jsonObj,elementName) {
return "</"+ (jsonObj.__prefix!=null? (jsonObj.__prefix+":"):"")+elementName+">";
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function jsonXmlSpecialElem ( jsonObj, jsonObjField ) {
if((config.arrayAccessForm=="property" && endsWith(jsonObjField.toString(),("_asArray")))
|| jsonObjField.toString().indexOf(config.attributePrefix)==0
|| jsonObjField.toString().indexOf("__")==0
|| (jsonObj[jsonObjField] instanceof Function) )
return true;
else
return false;
}
function jsonXmlElemCount ( jsonObj ) {
var elementsCnt = 0;
if(jsonObj instanceof Object ) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) )
continue;
elementsCnt++;
}
}
return elementsCnt;
}
function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
return config.jsonPropertiesFilter.length == 0
|| jsonObjPath==""
|| checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
}
function parseJSONAttributes ( jsonObj ) {
var attrList = [];
if(jsonObj instanceof Object ) {
for( var ait in jsonObj ) {
if(ait.toString().indexOf("__")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {
attrList.push(ait);
}
}
}
return attrList;
}
function parseJSONTextAttrs ( jsonTxtObj ) {
var result ="";
if(jsonTxtObj.__cdata!=null) {
result+="<![CDATA["+jsonTxtObj.__cdata+"]]>";
}
if(jsonTxtObj.__text!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj.__text);
else
result+=jsonTxtObj.__text;
}
return result;
}
function parseJSONTextObject ( jsonTxtObj ) {
var result ="";
if( jsonTxtObj instanceof Object ) {
result+=parseJSONTextAttrs ( jsonTxtObj );
}
else
if(jsonTxtObj!=null) {
if(config.escapeMode)
result+=escapeXmlChars(jsonTxtObj);
else
result+=jsonTxtObj;
}
return result;
}
function getJsonPropertyPath(jsonObjPath, jsonPropName) {
if (jsonObjPath==="") {
return jsonPropName;
}
else
return jsonObjPath+"."+jsonPropName;
}
function parseJSONArray ( jsonArrRoot, jsonArrObj, attrList, jsonObjPath ) {
var result = "";
if(jsonArrRoot.length == 0) {
result+=startTag(jsonArrRoot, jsonArrObj, attrList, true);
}
else {
for(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
result+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
result+=parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath,jsonArrObj));
result+=endTag(jsonArrRoot[arIdx],jsonArrObj);
}
}
return result;
}
function parseJSONObject ( jsonObj, jsonObjPath ) {
var result = "";
var elementsCnt = jsonXmlElemCount ( jsonObj );
if(elementsCnt > 0) {
for( var it in jsonObj ) {
if(jsonXmlSpecialElem ( jsonObj, it) || (jsonObjPath!="" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath,it))) )
continue;
var subObj = jsonObj[it];
var attrList = parseJSONAttributes( subObj )
if(subObj == null || subObj == undefined) {
result+=startTag(subObj, it, attrList, true);
}
else
if(subObj instanceof Object) {
if(subObj instanceof Array) {
result+=parseJSONArray( subObj, it, attrList, jsonObjPath );
}
else if(subObj instanceof Date) {
result+=startTag(subObj, it, attrList, false);
result+=subObj.toISOString();
result+=endTag(subObj,it);
}
else {
var subObjElementsCnt = jsonXmlElemCount ( subObj );
if(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath,it));
result+=endTag(subObj,it);
}
else {
result+=startTag(subObj, it, attrList, true);
}
}
}
else {
result+=startTag(subObj, it, attrList, false);
result+=parseJSONTextObject(subObj);
result+=endTag(subObj,it);
}
}
}
result+=parseJSONTextObject(jsonObj);
return result;
}
this.parseXmlString = function(xmlDocStr) {
var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
if (window.DOMParser) {
var parser=new window.DOMParser();
var parsererrorNS = null;
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
try {
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
//throw new Error('Error parsing XML: '+xmlDocStr);
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
}
else {
// IE :(
if(xmlDocStr.indexOf("<?")==0) {
xmlDocStr = xmlDocStr.substr( xmlDocStr.indexOf("?>") + 2 );
}
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlDocStr);
}
return xmlDoc;
};
this.asArray = function(prop) {
if (prop === undefined || prop == null)
return [];
else
if(prop instanceof Array)
return prop;
else
return [prop];
};
this.toXmlDateTime = function(dt) {
if(dt instanceof Date)
return dt.toISOString();
else
if(typeof(dt) === 'number' )
return new Date(dt).toISOString();
else
return null;
};
this.asDateTime = function(prop) {
if(typeof(prop) == "string") {
return fromXmlDateTime(prop);
}
else
return prop;
};
this.xml2json = function (xmlDoc) {
return parseDOMChildren ( xmlDoc );
};
this.xml_str2json = function (xmlDocStr) {
var xmlDoc = this.parseXmlString(xmlDocStr);
if(xmlDoc!=null)
return this.xml2json(xmlDoc);
else
return null;
};
this.json2xml_str = function (jsonObj) {
return parseJSONObject ( jsonObj, "" );
};
this.json2xml = function (jsonObj) {
var xmlDocStr = this.json2xml_str (jsonObj);
return this.parseXmlString(xmlDocStr);
};
this.getVersion = function () {
return VERSION;
};
}
}))
// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "";
jQuery.getJSON( "https://service1.homepro.com/smart.asmx/GetFAP_ProfileReviewsJSON?bid=141772&sort=1&page=1", function( data ) {
var xmlText = data,
x2js = new X2JS(),
jsonObj = x2js.xml_str2json( xmlText ),
html = '<div class="flex-wrapper">';
// console.log(jsonObj.SMART);
jQuery.each( jsonObj.SMART.XMLJSON, function( key, answer ) {
html += '<div class="flex-shell testimonial">';
html += '<div class="flex-item">';
html += '<div>';
html += '<span class="review-number"><i>' + answer.Quality + '</i> Quality of work</span>' ;
html += '<span class="review-number"><i>' + answer.Time + '</i> Timeliness</span>' ;
html += '<span class="review-number"><i>' + answer.Budget + '</i> Value for Money</span>' ;
html += '<span class="review-number"><i>' + answer.Courtesy + '</i> Courtesy</span>' ;
html += '<span class="review">' + answer.Testimonial + '</span>' ;
html += '<span class="name">' + answer.RefName + ' - ' + answer.refDate + '</span>';
html += '</div>';
html += '</div>';
html += '</div>';
});
jQuery('.start').html(html);
});
//above here
});
Apologies if I've gone about this in the wrong way. I've done;
npm install xml2json
Which didn't flag up any errors but I still can't seem to get the data to load correctly.
Solution that after you import <script> from package x2js, you should use window.X2JS to get constructor of X2JS. Almost packages implementing for both NPM and browser, the browser version usually use via object window, because it is shared and free connected in almost browsers.
This is my demo for the solution: https://jsfiddle.net/huynhsamha/2evdgt7r/
In my demo, I've include package x2js from NPM here https://unpkg.com/x2js#3.2.3/x2js.js
var X2JS = window.X2JS;
var x2js = new X2JS();
const data = {
a: {
b: 1
},
c: [1, 2]
}
console.log(x2js.js2xml(data))
// <a><b>1</b></a><c>1</c><c>2</c>

Need to work this string in as a parameter in my url

I have a filter script that ads a value to my url trough a set of checkboxes. Each checkbox group can only ad one value.
First click on a checkboxgroup looks like this:
/Network-CAT-cables?fss=yellow
Where the fss=yellow is the added parameter. A click on another chekcbox group would look like this:
/Network-CAT-cables?fss=yellow+cat6
If I check another checkbox in one of the above groups it replaces the previous value.
Now i need to add a parameter that looks like this:
&sps=d211av450240_2.0
If I set that as a value in the checkbox it kinda work. It ads the parameter and sort after it. And if i add a "normal" value it places before it. and that works too - like this:
?fss=yellow+cat5&sps=d211av450240_2.0
The problem is that when I have several of the new custom parameter in a group. In the other checkbox groups I can only have one value - and the chosen one replaces the old parameter. with the custom parameter I want to add it just ads on, instead of replaceing - like this.
?fss=yellow+cat5&sps=d211av450240_2.0+&sps=d211av450240_1.0
The correct outcome would have been
?fss=yellow+cat5&sps=d211av450240_1.0
I know this is because of the "&" in the parameter - but unsure how to work it out. I cant change the parameter either - and I know checkboxes are ment to be for multiple choices, but its like this for a reason.
My filterscript:
$(document).ready(function(){
new function(settings) {
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;
jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^\s*[0-9]+\s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^\s*|\s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};
var queryObject = function(a) {
var self = this;
self.keys = {};
if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
self.parseNew.apply(self, arguments);
}
return self;
};
queryObject.prototype = {
queryObject: true,
parseNew: function(){
var self = this;
self.keys = {};
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");
if (!key) return;
if ($numbers) {
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}
val = (!val && val !== 0) ? true : val;
self.SET(key, val);
});
});
return self;
},
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};
build(this.keys);
if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));
return queryString.join("");
}
};
return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object
function removeFSS() {
ga("send", "event", "button", "click", "filter-clear", "input");
var t = encodeURI(unescape($.query.set("fss", '')));
var n = window.location.href.split("?")[0]; window.location.href = n + t
}
function getFSS() {
var D = jQuery('.filterGenius input, .filterGenius select').serializeArray();
var O = {};
jQuery.each(D, function(_, kv) {
if (O.hasOwnProperty(kv.name)) {
O[kv.name] = jQuery.makeArray(O[kv.name]);
O[kv.name].push(clean(kv.value, ""));
}
else {
O[kv.name] =kv.value;
}
});
var V = [];
for(var i in O)
if(jQuery.isArray(O[i]))
V.push(O[i].join("+"));
else
V.push(O[i]);
V = jQuery.grep(V,function(n){ return(n) });
return V.join("+");
}
$(document).ready(function () {
$(".filterGenius input").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr("checked", "checked")
}
});
$(".filterGenius select option").each(function () {
if (window.location.href.indexOf($(this).val()) >= 0) {
$(this).attr('selected', true);
}
});
$(".filterGenius input, .filterGenius select").change(function () {
var s = encodeURI(unescape(jQuery.query.set("fss", getFSS())));
var o = window.location.href.split("?")[0];
$(".filterGenius input, .filterGenius select").attr("disabled", true);
window.location.href = o + s
});
});
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
});

Easy way to get multi-level javascript object property

I always need to deal with multi-level js objects where existence of properties are not certain:
try { value1 = obj.a.b.c; } catch(e) { value1 = 1; }
try { value2 = obj.d.e.f; } catch(e) { value2 = 2; }
......
Is there an easier way or a generic function (e.g. ifnull(obj.d.e.f, 2) ) that does not require a lot of try catches?
var value1 = (obj.a && obj.a.b && obj.a.b.c) || 1;
http://jsfiddle.net/DerekL/UfJEQ/
Or use this:
function ifNull(obj, key, defVal){
var keys = key.split("."), value;
for(var i = 0; i < keys.length; i++){
if(typeof obj[keys[i]] !== "undefined"){
value = obj = obj[keys[i]];
}else{
return defVal;
}
}
return value;
}
var value1 = ifNull(obj, "a.b.c", 1);
You could always create a helper function.
function isUndefined(root, path, defaultVal) {
var parts = path.split('.'),
i = 0,
len = parts.length,
o = root || {}, v;
while ((typeof (v = o[parts[i]]) === 'object', o = v) && ++i < len);
return (typeof v === 'undefined' || i !== len)? defaultVal: v;
}
var obj = {a: { b: { test: 'test' }}}, v;
v = isUndefined(obj, 'a.b.test', 1); //test
v = isUndefined(obj, 'a.test', 1); //1
Using lodash you can do this easily**(node exists and empty check for that node)**..
var lodash = require('lodash-contrib');
function invalidateRequest(obj, param) {
var valid = true;
param.forEach(function(val) {
if(!lodash.hasPath(obj, val)) {
valid = false;
} else {
if(lodash.getPath(obj, val) == null || lodash.getPath(obj, val) == undefined || lodash.getPath(obj, val) == '') {
valid = false;
}
}
});
return valid;
}
Usage:
leaveDetails = {
"startDay": 1414998000000,
"endDay": 1415084400000,
"test": { "test1" : 1234 }
};
var validate;
validate = invalidateRequest(leaveDetails, ['startDay', 'endDay', 'test.test1']);
it will return boolean.

Sorting two similar tables simultaneously

I've two tables which has exactly same columns. These tables are placed besides each other. Currently they are sorted separately. I want them to be sorted together. i.e. when I click on first column header of table 1 both tables should be sorted as if both are a single table.
This is the .js which I am using
function SortableTable (tableEl) {
this.tbody = tableEl.getElementsByTagName('tbody');
this.thead = tableEl.getElementsByTagName('thead');
this.tfoot = tableEl.getElementsByTagName('tfoot');
this.getInnerText = function (el) {
if (typeof(el.textContent) != 'undefined') return el.textContent;
if (typeof(el.innerText) != 'undefined') return el.innerText;
if (typeof(el.innerHTML) == 'string') return el.innerHTML.replace(/<[^<>]+>/g,'');
}
this.getParent = function (el, pTagName) {
if (el == null) return null;
else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())
return el;
else
return this.getParent(el.parentNode, pTagName);
}
this.sort = function (cell) {
var column = cell.cellIndex;
var itm = this.getInnerText(this.tbody[0].rows[1].cells[column]);
var sortfn = this.sortCaseInsensitive;
if (itm.match(/\d\d[-]+\d\d[-]+\d\d\d\d/)) sortfn = this.sortDate; // date format mm-dd-yyyy
if (itm.replace(/^\s+|\s+$/g,"").match(/^[\d\.]+$/)) sortfn = this.sortNumeric;
this.sortColumnIndex = column;
var newRows = new Array();
for (j = 0; j < this.tbody[0].rows.length; j++) {
newRows[j] = this.tbody[0].rows[j];
}
newRows.sort(sortfn);
if (cell.getAttribute("sortdir") == 'down') {
newRows.reverse();
cell.setAttribute('sortdir','up');
} else {
cell.setAttribute('sortdir','down');
}
for (i=0;i<newRows.length;i++) {
this.tbody[0].appendChild(newRows[i]);
}
}
this.sortCaseInsensitive = function(a,b) {
aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]).toLowerCase();
bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]).toLowerCase();
if (aa==bb) return 0;
if (aa<bb) return -1;
return 1;
}
this.sortDate = function(a,b) {
aa = thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]);
bb = thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]);
date1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
date2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
if (date1==date2) return 0;
if (date1<date2) return -1;
return 1;
}
this.sortNumeric = function(a,b) {
aa = parseFloat(thisObject.getInnerText(a.cells[thisObject.sortColumnIndex]));
if (isNaN(aa)) aa = 0;
bb = parseFloat(thisObject.getInnerText(b.cells[thisObject.sortColumnIndex]));
if (isNaN(bb)) bb = 0;
return aa-bb;
}
// define variables
var thisObject = this;
var sortSection = this.thead;
// constructor actions
if (!(this.tbody && this.tbody[0].rows && this.tbody[0].rows.length > 0)) return;
if (sortSection && sortSection[0].rows && sortSection[0].rows.length > 0) {
var sortRow = sortSection[0].rows[0];
} else {
return;
}
for (var i=0; i<sortRow.cells.length; i++) {
sortRow.cells[i].sTable = this;
sortRow.cells[i].onclick = function () {
this.sTable.sort(this);
return false;
}
}
}
There are just two columns and are likely to remain the same. Some ideas would be really appreciated.
I don't quite follow the HTML you have (since you didn't include any HTML), so I created a simple version myself here and implemented a sort across tables. The basic idea is that it collects all the data out of the tables into a single javascript data structure, sorts the javascript data structure and then puts all the data back into the tables.
This makes the sorting much simpler and the only places you have to deal with the complexities of multiple tables is when retrieving the data and then putting it back into the tables. You can see it work here: http://jsfiddle.net/jfriend00/Z5ywA/. Just click on a column header to see both tables sorted by that column.
The code is this:
function sortTables(colNum) {
var t1 = document.getElementById("table1");
var t2 = document.getElementById("table2");
var data = [], sortFn;
function sortAlpha(a, b) {
// deal with empty strings
var aa = a[colNum].data, bb = b[colNum].data;
if (!aa) {
return(!bb ? 0 : -1);
} else if (!bb){
return(1);
} else {
return(aa.localeCompare(bb));
}
}
function sortNumeric(a, b) {
// deal with possibly empty strings
var aa = a[colNum].data, bb = b[colNum].data;
if (typeof aa == "string" || typeof bb == "string") {
return(sortAlpha(a, b));
} else {
return(aa - bb);
}
}
// get the data
function getData(table) {
var cells, rowData, matches, item, cellData;
var rows = table.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rowData = [];
cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// add each cell in the row to the rowData data structure
item = {};
item.origStr = cells[j].textContent || cells[j].innerText;
cellData = item.origStr.replace(/^\s*|\s*$/g, "").toLowerCase();
if (cellData.match(/^[\d\.]+$/)) {
cellData= parseFloat(cellData);
} else if (matches = cellData.match(/^(\d+)-(\d+)-(\d+)$/)) {
cellData= new Date(
parseInt(matches[3], 10),
parseInt(matches[1], 10) - 1,
parseInt(matches[2], 10)
);
}
item.data = cellData;
// determine the type of sort based on the first cell we find
// with data in the column that we're sorting
if (!sortFn && item.data !== "" && j == colNum) {
if (typeof item.data == "number" || typeof item.data == "object") {
sortFn = sortNumeric;
} else {
sortFn = sortAlpha;
}
}
rowData.push(item);
}
// add each row to the overall data structure
data.push(rowData);
}
}
// put data back into the tables
function putData(table) {
var cells, rowData, item;
var rows = table.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// add each cell in the row to the rowData data structure
cells[j].innerHTML = data[0][j].origStr;
}
// remove this row
data.shift();
}
}
getData(t1);
getData(t2);
data.sort(sortFn);
putData(t1);
putData(t2);
return(false);
}
​ ​

Categories