how to form json structure in javascript - javascript

All, I have a module to import CSV file and fetch data and display in a grid. Fetched the data in array but I expected value must be in a particular JavaScript data structure.
Here my sample code
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
var lines = [];
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
var tarr = [];
for (var j=0; j<headers.length; j++) {
tarr.push(headers[j]+":"+data[j]);
}
lines.push(tarr);
// console.log(lines)
}
}
console.log("details ="+lines)
});
allText Value
serial,Asset Type,id
Asset1,Equipemnt,id1
Asset2,Equipemnt,id2
Asset3,Equipemnt,id3
Asset4,Equipemnt,id4
My output:
Serial:Asset1,Asset Type:Equipment,id:RF0001,
Serial:Asset2,Asset Type:Equipment,id:R0002,
Serial:Asset3,Asset Type:Equipment,id:R0003,
Serial:Asset4,Asset Type:Equipment,id:F0004,
Serial:Asset5,Asset Type:Equipment,id:F0005,
Serial:Asset6,Asset Type:Equipment,id:0006,
Serial:Asset7,Asset Type:Equipment,id:007,
Expected structure:
{
serial:["Asset1","Asset1","Asset2","Asset3","Asset4"],
Asset Type:["Equipment","Equipment","Equipment","Equipment","Equipment"],
id:["id1","id2","id3","id4",]
}
How to achieve this structure?

function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
console.log("headers-->"+headers)
//initializing resulting json
var lines = {};
//initializing arrays for all the headers
for(var i=0; i<headers.length; i++){
lines[headers[i]] = [];
}
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
if (data.length == headers.length) {
for (var j=0; j<headers.length; j++) {
lines[headers[j]].push(data[j]);
}
}
}
return lines
}
//format all text is taken up (I tested on a string)
allText = "serial,Asset Type,id\n Asset1,Equipemnt,id1\nAsset2,Equipemnt,id2\nAsset3,Equipemnt,id3\nAsset4,Equipemnt,id4"
Result :

You first line is header and wanted to set as a key object . So you already get that var headers = allTextLines[0].split(','); thus assign that object key by object[key] = value format .
I assume that your header and lines splited key has the same thus I loop allTextLines and used the same key for both headers and allTextLines !!
var all = "serial,Asset Type,id \n"+
"Asset1,Equipemnt,id1 \n"+
"Asset2,Equipemnt,id2 \n"+
"Asset3,Equipemnt,id3 \n"+
"Asset4,Equipemnt,id4";
processData(all);
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
var headers = allTextLines[0].split(',');
var lines = {};
//set headers as key
for(var i = 0 ; i < headers.length;i++) {
lines[headers[i]] = [];
}
//assign relative value to key
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
for(var d in data) {
lines[headers[d]].push(data[d]);
}
}
console.log(lines)
}

Related

Var not being used in object.var

function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
var data = sheet.getDataRange().getValues();
var range = sheet.getRange("A1:L" + data.length);
range.sort(1);
const people = {};
for(var i = 0; i < data.length; i++) {
var name = data[i][0] + data[i][1];
console.log(i);
if (!people.name) {people.name = {rows: [i]};} else {people.name.rows.push(i)}
}
Logger.log(people);
}
What should I be doing differently? At the end, it logs {name={rows=[0.0, 1.0, 2.0, ...]}} instead of having an object for each name...?
In the sheet there's just a first name and last name on columns A and B, for around 80 rows.
Use the bracket syntax if you want to use dynamic names for properties: https://riptutorial.com/javascript/example/2321/dynamic---variable-property-names
In your case:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data');
var data = sheet.getDataRange().getValues();
var range = sheet.getRange("A1:L" + data.length);
range.sort(1);
const people = {};
for(var i = 0; i < data.length; i++) {
var name = data[i][0] + data[i][1];
console.log(i);
if (!people[name]) {people[name] = {rows: [i]};} else {people[name].rows.push(i)}
}
Logger.log(people);
}

Cannot convert [object Object] to (class)

I am trying to count the number of rows between two rows containing particular words in google sheets. But I am getting the following error:
Cannot convert [object Object] to (class). (line 41, file "Code")
I have written the following code on the google app script:
function search(SPREADSHEET_ID, SHEET_NAME, word) {
var locatedCells = [];
var ss = SpreadsheetApp.openById(SPREADSHEET_ID);
var searchLocation = ss.getSheetByName(SHEET_NAME).getDataRange().getValues();
//Loops to find the search term.
for (var j = 0, jLen = searchLocation.length; j < jLen; j++) {
for (var k = 0, kLen = searchLocation.length; k < kLen; k++) {
var find = word;
if (find == searchLocation[j][k]) {
locatedCells.push({ 'found': (j + 1)});
}
}
}
// Logger.log(locatedCells);
return(locatedCells)
}
function footerlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Footers"
var footerlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(footerlocation);
return(footerlocation)
}
function keywordlocation(){
var SPREADSHEET_ID = "1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4"
var SHEET_NAME = "Bedding"
var word = "Keyword Page Redirects to Implement"
var keywordlocation = search(SPREADSHEET_ID, SHEET_NAME, word)
//Logger.log(keywordlocation);
return(keywordlocation)
}
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()
var endrow= keywordlocation()
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}
I would appreciate if someone could help me with this.
I was able to figure out the solution, change the count function to the following:
function count(){
var sheet= SpreadsheetApp.openById("1nYBEuMMC4j1A4qryzKKq33PsTRH54ADyJLsEoTmbKh4").getSheetByName("Bedding");
var startrow=footerlocation()[0]['found']
var endrow= keywordlocation()[0]['found']
var range = sheet.getRange(startrow,1,endrow-startrow,1);
var datas = range.getValues();
var count = 0;
for (data in datas) {
for (cell in data) {
//Logger.log(typeof cell) //{
count++;
//}
}
}
Logger.log(data)
}

How to rewrite from new array method to literal array method in Javascript

Hi I have captured the data from a google spreadsheet to a new array like this
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
//$.getJSON("http://cors.io/spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length;
for (var i=0; i<len; i++) {
//first row "title" column
resultData[i]=new Array(9);
resultData[i][1]=data.feed.entry[i].gsx$constituency.$t;
resultData[i][2]=data.feed.entry[i].gsx$winner2010.$t;
resultData[i][3]=data.feed.entry[i].gsx$winningparty.$t;
resultData[i][4]=data.feed.entry[i].gsx$candidatename1.$t;
resultData[i][5]=data.feed.entry[i].gsx$party1.$t;
resultData[i][6]=data.feed.entry[i].gsx$candidatename2.$t;
resultData[i][7]=data.feed.entry[i].gsx$party2.$t;
resultData[i][8]=data.feed.entry[i].gsx$candidatename3.$t;
resultData[i][9]=data.feed.entry[i].gsx$party3.$t;
}
});
How can I rewrite the above as a literal array like below
var colors = [gsx$constituency, gsx$winner2010];
I am still learning to write code so will appreciate any help
I think you should update your code like below:
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
data.feed.entry.forEach(function(singleEntry) {
var resultData = [];
resultData.push(singleEntry);
})
});
Now you can get data like resultData[index].gsx$constituency.
Here is a way to put all values in 2-dimensional array :
var resultData = [];
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length, entries = data.feed.entry;
for (var i=0; i<len; i++) {
var row = [];
for (var name in entries[i]) row.push(entries[i][name].$t);
resultData.push(row);
}
console.log('result:', resultData);
});
Fiddle : http://jsfiddle.net/5zycjq7c/
$.getJSON("https://spreadsheets.google.com/feeds/list/1IoNqeReOPKNFrYMlK2rnJVuMaLeAgnZneLbKYSQ7bs4/od6/public/values?alt=json", function(data) {
var len = data.feed.entry.length;
for (var i=0; i<len; i++) {
//first row "title" column
var current = data.feed.entry[i];
resultData[i]= [current.gsx$constituency.$t, current.gsx$winner2010.$t, current.gsx$winningparty.$t, ...]; // include all here
}
});

displaying table in the right style

I have a problem in displaying the borders of my table correctly ,I work with jsPDF library ,this is the result that I get :
this is my code that selecet every row and display the data:
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length,i<5; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length;i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length,j<5 ; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function callme(){
var table = tableToJson($('#table').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(j=="email"){
doc.cell(1,10,190,20,cell,i);
}
else{
doc.cell(1,10,100,20,cell,i);
}
});
});
thanks for help

How to add dynamically HTML element using JavaScript and Firefox Add-on SDK

I am developing a simple add-on with Firefox SDK that allows the user to review the stored data.
I would like to show the items in a panel with a table. The table is created dynamically with the data incoming from the data-base. Firstly, In the JavaScript code I create the items with their properties, then I create a table with the properties as row and I append the items with the value of each properties.
I have some problems: the table has only the item's name as first row and the properties name as first column without the value in the cells. It seems that the code is not executed in order, but it seems that the faster functions are executed first.
This is the code:
self.on('message', function() {
var container = $('#container');
container.empty();
items = [];
self.port.emit('getItem');
});
self.port.on('items', function(response) {
var ok = 0;
var items = [];
var table = $('#tableContainer #table').clone();
var container = $('#container');
table.append("<tr id=first><th> </th></tr>");
var json = eval('('+ response + ')');
for (var i = 0, len = json.length; i < len; ++i) {
var item = {
id: json[i],
properties: []
};
items.push(item);
}
items.forEach ( function(item) {
table.find('#first').append("<th id="+item.id+">"+item.id+"</th>");
self.port.emit('detailsItem', item.id);
self.port.on('details'+item.id, function(response) {
var details = eval('('+ response + ')');
var description = [];
ndet = details.length;
var len = details.length;
for (var i = 0; i < len;) {
var detail = {
dimension : details[i].dimension,
value : details[i].value
}
description.push(detail);
++i;
}
item.properties = description;
});
});
self.port.emit('getDimension');
self.port.on('dimension', function(response) {
var dimensions = eval('('+ response + ')');
for(var cont = 0, l = dimensions.length; cont < l; ++cont) {
table.append("<tr id=dimension"+cont+"><td>"+dimensions[cont]+"</td></tr>");
items.forEach( function(item) {
var prop = [];
prop = item.properties;
var lun = prop.length;
for( var p =0;p < lun;) {
if(item.properties[p].dimension == dimensions[cont]) { table.find('#dimension'+cont).append("<td>"+item.properties[p].value+"</td>");
}
else {
table.find('#dimension'+cont).append("<td> --- </td>");
}
++p; }
});
};
});
container.append(table);
});

Categories