Table json object in javascript - javascript

I want to make json object of html table in javascript.Currently I am able to read the each cells value in javascript, the only problem is that I am not able to retrieve as per my need so think of any suggestion here. Currently getting value like:
var x = document.getElementById("tableId");
for (var i = 0; i < x.rows.length; i++) {
for (var j = 0; j < x.rows[i].cells.length; j++){
tableJsonDTO[name] = x.rows[i].cells[j].innerHTML;
}
}
This is how i am able to read the each cell value.The table format is as follow:
header: company_1 company_2 company_3
Question1 answer_1 answer_1 answer_1
Question2 answer_2 answer_2 answer_2
and so on.How can i read the value so that i can get object like:
var obj = [{spname:"company_1",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_2",qalist:[{question:"",answer:""},{question:"",answer:""}]},{spname:"company_3",qalist:[{question:"",answer:""},{question:"",answer:""}]}]
Please give some suggestion.

You simply need to change the way you put values to tableJsonDTO. Demo.
document.getElementById('toJSON').addEventListener('click', function(){
var table = document.getElementById('mytable'),
names = [].slice.call(table.rows[0].cells),
values = [].slice.call(table.rows, 1),
out = {};
values.forEach(function(row) { //iterate over values
var cells = row.cells,
caption = cells[0].innerHTML; //get property name
[].forEach.call(cells, function(cell, idx) { //iterate over answers
var value = {},
arr;
if(!idx) return; //ignore first column
value[caption] = cell.innerHTML; //prepare value
//get or init array of values for each name
arr = out[names[idx].innerHTML] || (out[names[idx].innerHTML] = []);
arr.push(value);
});
});
console.log(out);
});

Related

pushing blank rows in the middle of an array google app script javascript

I have some data pulling from a sheet. I have created an array that is sorted by the 2nd column (SKU column) below is what is returned in the spreadsheet:
In this array would like to add a blank row when the SKU changes to make it easier to read. I wrote the following code:
function update(){
var mfgSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Order Info");
var purchaseLog = SpreadsheetApp.
openById("1KkR4jE1c00WuQpPrexW8f9BIq5vxl0fWaUGxbeYERsE").
getSheetByName("Order Details");
var orderSort = purchaseLog.getRange(3, 1, purchaseLog.getLastRow(), 15).getValues().
sort(function(r1,r2){
var a = r1[1];
var b = r2[1];
if(a>b){
return 1;
}else if (a<b){
return -1;}
return 0;
}).filter(function (item){if(item[1]!=""&&item[1]!="Purchase Order Link"){return true}})
.map(function(r){return [r[0],r[1],r[2],r[5],r[6],r[11],r[13],r[12],r[8]]});
var SKUs = orderSort.map(function(r){return r[1]})
var SKUList = [];
for (var i in SKUs) {
var SKU = SKUs[i];
var duplicate = false;
for (var j in SKUList) {
if (SKU === SKUList[j]) {
duplicate = true;
}
}
if (!duplicate) {
SKUList.push(SKU);
}
}
var finalArr = []
for(var i = 0; i <= SKUList.length-1; i++){
var element = orderSort.filter(function(item){if(item[1]===SKUList[i]){return true}});
finalArr.push(element);
finalArr.push([,,,,,,,,,]);
}
Logger.log(finalArr);
}
The code almost works, but I'm getting a weird 3d Array, and I'm afraid that my logic is very wrong. Photo of the log is also included. Anyone that could help me solve this problem, it would be greatly appreciated.
element is already a 2D array. By pushing it to another array, a 3D array is created. Use Array.concat instead:
finalArr = finalArr.concat(element);//instead of finalArr.push(element);

Continue iterating over a for loop after condition has been met Javascript

I have written that has a for loop that will run additional code if (sheetData[i] !== "").
Ideally, I would like to run the following code after the condition, but then loop back around and run it again for the next item that matches the condition. Any ideas on how I can achieve this?
function getSheetSectionDataTest(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Params"); // get sheet
var sheetData = sheet.getDataRange().getValues(); //get all sheet data
var sectionNames = normalizeHeaders(normalizeHeaders(sheet.getRange('A1:A').getValues()));
var sectionData = []; // main array to contain all section data
// create an array for each section
for(h = 0; h < sectionNames.length; h++) {
sectionData[sectionNames[h]] /*property name or key of choice*/
= [];
}
for (var i = 0; i < sheetData.length; i++){ //loop through each row in the spreadsheet
var sectionName = normalizeHeaders(sheetData[i]); //return normalized camelCase section name found in column A.
if (sheetData[i] !== ""){ // Test - stop at a cell that matches the criteria and return the data table.
var headerRow = normalizeHeaders(sheetData[i+1]); //define and normalize the table headers
for (var j = i+2; j < sheetData.length; j++) { //loop through each row in the data table.
if (sheetData[j][1] !== ""){ //if there are contents in the table keep looping.
var obj = {};
sectionData[sectionName[0]].push(obj); // Need to replace ranges with a dynamic variable that gives us the current sectionName value as an object?
for (var rowColumn = 0; rowColumn < headerRow.length; rowColumn++) { //loop through each column in the current row of the table.
obj[headerRow[rowColumn]]=sheetData[j][rowColumn+1];
}
}
else { //stop when an empty cell is reached
return sectionData; //when the data table loop runs into an empty cell stop loop and return the data
}
}
}
}
};

How to Compare two Object of Data's in JavaScript

Am having some id's in my "var " . That id's are all present in a Static data which is having both id with names . What i'm trying to do is i have to find out the name's of my id's and print the name's alone . I'm trying with many Underscore js method's but failed . Can some one clarify/Suggest me pls .
var CatePeri =[];
var cate =[];
// var CateName=[];
$scope.getCategories = function() {
for (var i = 0 ; i < mainSteps.length; i++) {
for (var j = 0; j<mainSteps[i].steps.length; j++) {
var CatePeri= mainSteps[i].steps[j].category;
cate.push(CatePeri);
// var CateName =_.findWhere(mainSteps[i].category, cate);
// var CateName =_.where(mainSteps[i].category, cate);
}
}
return cate; // It return Id's Now
// But i have to Return the name's of that id's
Here
var CatePeri is having Whole Category id's with Names,
var cate is having Category id's alone,
Instead of returning id's i need to Return their names .
var CatePeri =[];
var cate =[];
// var CateName=[];
$scope.getCategories = function() {
for (var i = 0 ; i < mainSteps.length; i++) {
for (var j = 0; j<mainSteps[i].steps.length; j++) {
var CatePeri= mainSteps[i].steps[j].category;
cate.push(CatePeri);
// var CateName =_.findWhere(mainSteps[i].category, cate);
// var CateName =_.where(mainSteps[i].category, cate);
}
}
return _.pick(_.values(cate), 'name'); // It return Id's Now
// But i have to Return the name's of that id's
I assumed,you Have a static JSON like below
var staticJson ={
id:'5rtf567',
name:'S'
}
Use underscore.js _.where option like,
// If you have the multiple object to find out the name put it the below code in `for` loop and try it
var nameOfId = _.where(staticJson ,{id:staticJson.id}
console.log('If you Want Whole Object',angular.toJson(nameOfId));
console.log('If you Want Name',angular.toJson(nameOfId.name));

Find the next key id in object

I stored an object in one variable (Consider as datatable).
var data=[{"controlID":"A","currentValue":"10","onChange":"","onClick":""},
{"controlID":"B","currentValue":"5","onChange":"Testing(A,B)","onClick":""},
{"controlID":"C","currentValue":"-5","onChange":"Testing1(A,B)","onClick":""},
{"controlID":"D","currentValue":"","onChange":"Testing2(B,C)","onClick":""},{"controlID":"E","currentValue":"","onChange":"Testing3(C,D)","onClick":""},{"controlID":"F","currentValue":"","onChange":"","onClick":""}];
Now I know the second row key value as B. How to I Get the Third row (i.e., "C" row values)
Am new of this field. Please help us to helpful.
This function will return your index:
var FindIndexOfControlID = function(id, data){
for(var i = 0; i < data.length ; i++){
if( data[i]['controlID'] == id ){
return i;
}
}
};
Usage:
var index = FindIndexOfControlID('C', data);
Live Example
http://jsfiddle.net/urahara/medhgm7b/
NOTE
Alternatively you may also want to implement function that returns index of any specified property and value:
var FindIndexOfProperty = function(value, property, data){
for(var i = 0; i < data.length ; i++){
if( data[i][property] == value ){
return i;
}
}
};
Usage
FindIndexOfProperty('-5', 'currentValue',data); // returns 2
You can return the third row in javascript by simply executing var thirdRow = data[2]. The row will be returned as an object.

How to get value of key from the array in java script

I have created static array as following below
country["0"]=[USA];
sate[country[0][0]]=[["NewYork","NY"],["Ohio,"Oh"]]
for (var i = 0; i < sate[country[0][0]].length; i++) {
var key = state[country[0][0]] [i][0];
var value = state[country[0][0]] [i][i+1];
}
from above loop i am able to get the keys of state like NewYork and Ohio.
Please help me how i will get the value of "NY" and "Oh"?
var value = state[country[0][0]] [i][1];
There are a couple or three errors in your code. Assuming country has a list of countries and state keeps the states of the country...
country = ["USA"];
state = {"USA": [["NewYork","NY"],["Ohio","Oh"]] };
for (var i = 0; i < state[country[0]].length; i++) {
var key = state[country[0]] [i][0];
var value = state[country[0]] [i][1];
}
You have mistyped here
sate[country[0][0]]=[["NewYork","NY"],["Ohio", "Oh"]]
and You can get ["NY", "Oh"] by using this:
for (var i = 0; i < sate[country[0][0]].length; i++) {
var key = state[country[0][0]] [i][0];
var value = state[country[0][0]] [i][1];
}

Categories