Dynamic table from JSON using javascript - javascript

I use the following json to develop a table structure. But I'm unable to go ahead on adding rows according to columns.
[
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys":[{
"username": "developer"
},{
"password": "password123"
}]
},
{
"type": "Testing",
"keys":[{
"username": "tester"
},{
"password": "password123"
}]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/developer"
}]
},
{
"type": "Testing",
"keys":[{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/development"
}]
},
{
"type": "Testing",
"keys":[{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},{
"url": "/demo/testing"
}]
}
]
}
]
I use the following script to iterate over the json.
var subTable = '<div class="subtable"><table data-clicked-parent-row="'+ clickedCell.row
+'" data-clicked-column="'+ clickedCell.column +'"><tr><th>Keys</th>';
tableData.forEach(function(e){
if(rowType == e.authType){
var phases;
e.phases.forEach(function(t){
subTable += '<th>'+ t.type +'</th>'
})
return subTable + '</tr></table></div>';
}
})
The thing is, I'm unable to add rows to the table while iterating on the objects. The following is a static version of the table. how can i write a generic function to achive the following table structure. Please let me know any better way to write the iteration.

var data = {
"Items": [
{
"id": "A004"
, "name": "ACC LR2"
, "userId": ["1","2","3","4"]
}, {
"id": "0001"
, "name": "ABG IT"
, "userId": ["8","9","10","11"]
}
]
}
function getUserId(obj){
result = []
obj.Items.forEach( function(item, i){
result.push(item.userId);
});
return result;
}
function getUserIdAll(obj){
result = []
obj.Items.forEach( function(item, i){
result = result.concat(item.userId);
});
return result;
}
console.log( getUserId(data) );
console.log( getUserIdAll(data) );
var data = [
{
"authType": "BasicAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"username": "developer"
},
{
"password": "password123"
}
]
},
{
"type": "Testing",
"keys": [
{
"username": "tester"
},
{
"password": "password123"
}
]
}
]
},
{
"authType": "AccessToken",
"phases": [
{
"type": "Development",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/developer"
}
]
},
{
"type": "Testing",
"keys": [
{
"token": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
},
{
"authType": "OAuth",
"phases": [
{
"type": "Development",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/development"
}
]
},
{
"type": "Testing",
"keys": [
{
"consumer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"customer_key": "9a0554259914a86fb9e7eb014e4e5d52"
},
{
"url": "/demo/testing"
}
]
}
]
}
];
function objGetKeyVal(obj){
for (var key in obj) {
return [ key, obj[key] ];
}
}
(function createTable(tableData){
var table = '<table>';
// tableHeader += '<caption>Caption</caption>';
// Creating table header
// table += '<tr>';
// table += '<th>Keys</th>';
// table += '<th>Development</th>';
// table += '<th>Testing</th>';
// table += '</tr>';
// Sub tables iterator
tableData.forEach(function(subTable, i){
tableRows = []; // Rows array for sub table
table += '<tr><th>Keys</th>'; // Table headers creating
subTable.phases.forEach(function(colData, icol){
table += '<th>'+colData.type+'</th>'; // Creating table headers for each phases
colData.keys.forEach(function(key, irow){ // Converts structured data to array of rows arrays of columns
if( tableRows[irow] === undefined) { tableRows[irow] = []; }
rowData = objGetKeyVal(key);
tableRows[irow][0] = rowData[0];
tableRows[irow][icol+1] = rowData[1];
});
});
table += '</tr>'; // End table header cration
// Now we have usual table array - need only convert it to HTML
// table looks like: [ ['col1', 'col2', 'col3'], ['col1', 'col2', 'col3'] ]
table += '<tr><th colspan="3">'+subTable.authType+'</th></tr>';
tableRows.forEach(function(row){
table += '<tr>';
row.forEach(function(str){
table += '<td>'+str+'</td>';
});
table += '</tr>';
});
});
table += '</table>';
$('body').append(table);
})(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Use this function for render table with json. Observe this function works with simple json. For complex json necessary adapter this function
var tableData = [
{
"Name": "Kevin",
"Adress": "Adress UHE, SC",
},
{
"Name": "Jose",
"Adress": "Adress KUK, CC",
},
{
"Name": "Kevin",
"Adress": "Adress CGH, JK",
}
];
function compile(){
var subTable = '', column = '', row = '';
for(c in tableData[0])
column += '<th>' + c + '</th>';
for(item in tableData){
row += '<tr>';
for(c in tableData[0]) row += '<td>' + tableData[item][c] + '</td>';
row += '</tr>';
}
console.log(row)
return '<table border="solid 1px"><tr>' + column + '</tr>' + row + '</table>';
};
document.write(compile());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Loop fetches all the words in 1 input field

as you can see in the picture below, my words 'es' and 'presso' are put into one input field instead of 'es' in one and 'presso' in another input field.
how my JSON looks like:
{
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
}
This is how my loop looks like:
$.map(exercise, function(exercise, i) {
$("#addOpdracht").click();
$(".exerciseGetWordInput_" + i).val(exercise.word) // starts with 0
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
});
to zoom in on the loop where I fetch the syllables:
var exerSyll = json.main_object.main_object.exercises;
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$(".syllable" + s).val(exer.syllables);
});
the function where I create the syllable inputs:
function getWordPartInput(id, cValue){
cValue = cValue || '';
var wpInput = $('<input/>', {
'class': 'form-group form-control syllable' + SyllablesID++,
'type': 'text',
'value': cValue,
'placeholder': 'Syllables',
'name': 'Syllablescounter['+ SyllablesID++ +']'
});
return wpInput;
}
what is it that I am doing wrong? (I did declare the variable SyllablesID so don't worry about that part).
var data = {
"main_object": {
"id": "new",
"getExerciseTitle": "Example",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
"title": "Example",
"language": "nl_NL",
"exercises": [
{
"word": "espresso",
"syllables": [
"es",
"presso",
"",
""
]
}
]
},
"dataType": "json"
}
};
function draw(data){
for (ex of data.main_object.main_object.exercises){
for( sy of ex.syllables){
$("#container").append(`<input type="text" value="${sy}">`)
}
}
}
draw(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container"><div>
syllables is an array as per to posted JSON so you'll have to get each value and add it as a value to the input element. You can again use .map or for/forEach etc to loop through syllabus array and add the array entries to input values
$.map(exerSyll, function(exer, s) {
console.log(exer.syllables);
$.map(exer.syllables, function(syll, i){
$(".syllable" + i).val(syll);
})
});

Nesting Json Data with jquery

I have this data from a csv file that i have to use in a dependant dropdown with jquery. I can't figure out if it is possible to nest the data i received for what i already have coded.
CSV file
Banco Tarjeta Cuotas Medio_Pago Coeficiente TEA CFT
Santander Visa 1 modulodepago2 1 0.00% 0.00%
Santander Visa 1 nps 1.0262 18.56% 22.84%
Frances Visa 1 modulodepago2 1 0.00% 0.00%
Frances Master 2 nps 1.0262 18.56% 22.84%
My json data comes like this
[{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"modulodepago2",
"coeficiente":"1","tea":"0.00%","cft":"0.00%"},
{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"nps",
"coeficiente":"1.0262","tea":"18.56%","cft":"22.84%"} ...
etc...
Is there a way i can nest this json data like this (+ adding unique names and id's)?
var myJson = {
"banco": [
{
"name": "Santander",
"id": "Santander",
"tarjeta": [
{
"name": "Visa",
"id": "SantanderVisa",
"cuotas": [
{
"name": "1",
"id": "SantanderVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
},
{
"name": "1",
"id": "SantanderVisa2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
},
{
"name": "Frances",
"id": "Frances",
"tarjeta": [
{
"name": "Visa",
"id": "FrancesVisa",
"cuotas": [
{
"name": "1",
"id": "FrancesVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
}
]
},
{
"name": "Master",
"id": "FrancesMaster",
"cuotas": [
{
"name": "2",
"id": "FrancesMaster2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
}
]
}
You will need to group by keys. An easy way to do this is to use Lodash or Underscore.js.
I used Papa Parse to convert the CSV data into JSON.
var csvData = $('#csv-data').text().trim();
var jsonData = Papa.parse(csvData, { delimiter:',', header:true }).data;
var transformedJson = {
banco : _.chain(jsonData)
.groupBy('Banco')
.toPairs()
.map(banco => {
return {
name : banco[0],
id: banco[0],
tarjeta : _.chain(banco[1])
.groupBy('Tarjeta')
.toPairs()
.map(tarjeta => {
return {
name: tarjeta[0],
id: banco[0] + tarjeta[0],
cuotas: _.map(tarjeta[1], cuota => {
return {
name: cuota['Cuotas'],
id: banco[0] + tarjeta[0] + cuota['Cuotas'],
medio_pago: cuota['Medio_Pago'],
coeficiente: cuota['Coeficiente'],
tea: cuota['TEA'],
cft: cuota['CFT']
}
})
};
})
}
}).value()
}
console.log(JSON.stringify(transformedJson, null, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.4/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<textarea id="csv-data" style="display:none" rows="5" cols="72">
Banco,Tarjeta,Cuotas,Medio_Pago,Coeficiente,TEA,CFT
Santander,Visa,1,modulodepago2,1,0.00%,0.00%
Santander,Visa,1,nps,1.0262,18.56%,22.84%
Frances,Visa,1,modulodepago2,1,0.00%,0.00%
Frances,Master,2,nps,1.0262,18.56%,22.84%
</textarea>
try something like this
you get all medio_pago for the others objects you just use the object name.
I haven't tested it but I'm sure this will work for you.
var Json = ...
$.each(Json, function(i, item) {
alert(myJson[i].banco.tarjeta.cuotas.medio_pago);
});

JSON nested Parsing Help using $.each

Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};

How To Get JSON Hierarchy Values

Hi All, How can I get the id value by using JQuery Mobile, Thanks
Here I Attach The Code, I just only want to display the id or alert msg for testing, many thanks
{"total_rows":7,"offset":0,"rows":[
{
"id":"637184110f5faea091fdbdcf618a353a",
"key":"637184110f5faea091fdbdcf618a353a",
"value":{"rev":"1-f59c856e98e1c5f11578562778d8cf3b"}
},
{
"id":"637184110f5faea091fdbdcf618b85d2",
"key":"637184110f5faea091fdbdcf618b85d2",
"value":{"rev":"1-17731aef6d1d52e0d2ad03e2772d1a0a"}
}
]
}
var obj = {
"total_rows": 7,
"offset": 0,
"rows": [
{
"id": "637184110f5faea091fdbdcf618a353a",
"key": "637184110f5faea091fdbdcf618a353a",
"value": {
"rev": "1-f59c856e98e1c5f11578562778d8cf3b"
}
}, {
"id": "637184110f5faea091fdbdcf618b85d2",
"key": "637184110f5faea091fdbdcf618b85d2",
"value": {
"rev": "1-17731aef6d1d52e0d2ad03e2772d1a0a"
}
}
]
};
for (id in obj.rows) {
alert(obj.rows[id].id);
}
jsonObj = {
"total_rows": 7,
"offset": 0,
"rows": [
{
"id": "637184110f5faea091fdbdcf618a353a",
"key": "637184110f5faea091fdbdcf618a353a",
"value": {
"rev": "1-f59c856e98e1c5f11578562778d8cf3b"
}
},
{
"id": "637184110f5faea091fdbdcf618b85d2",
"key": "637184110f5faea091fdbdcf618b85d2",
"value": {
"rev": "1-17731aef6d1d52e0d2ad03e2772d1a0a"
}
}
]
}
var rowsArray = jsonObj["rows"] //alternatively jsonObj.rows
for (row in rowsArray) {
console.log(row.id); //alternatively row["id"]
alert(row.id); //alternatively row["id"]
}
Why do you need jQuery mobile for this json?
EDIT With $.each
Since you are hell bent on using jQuery
var rowsArray = jsonObj["rows"]
$.each(rowsArray, function(i, row) {
alert(rowsArray[i].id);
});​
$.each(rowsArray, function(i, row) {
alert(row.id);
});​
var jsonObj = '{
"total_rows":7,
"offset":0,
"rows":[
{
"id":"637184110f5faea091fdbdcf618a353a",
"key":"637184110f5faea091fdbdcf618a353a",
"value":{
"rev":"1-f59c856e98e1c5f11578562778d8cf3b"
}
},
{
"id":"637184110f5faea091fdbdcf618b85d2",
"key":"637184110f5faea091fdbdcf618b85d2",
"value":{
"rev":"1-17731aef6d1d52e0d2ad03e2772d1a0a"
}
}
]
}';
First you can even do this without using jQuery.
Without jQuery:-
for(i=0; i< string.rows.length; i++){
alert(string.rows[i].id);
alert(string.rows[i].key);
alert((string.rows[i].value.rev));
}
With jQuery
$.each(jsonObj, function(key, value){
console.log(key, value);
})

Accessing second array in a JSON decode using Jquery

I need to access the second array from a JSON decoded string, but I am having no luck.
The entire JSON string is displayed in var RAW00, and then split into var RAW01 & var RAW02.
All 3 of these are for testing - RAW00 is identical to msg
When they are split - I can access either, depending on what variable I start of with, but when I use RAW00 I cannot access the tutor section.
I will provide more detail if required, but my question is:
How do I see and access the tutor array in the second $.each (nested) block??]
Thanks :-)
success: function(msg)
{
var test = "";
var raw00 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
},
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
var raw01 = {
"allData": [
{
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
]
}
]
};
var raw02 = {
"allData": [
{
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
]
};
$.each(raw00.allData, function(index, entry)
{
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.name+'</td></tr>';
});
$('#all-courses-table-content').html( test );
});
You need to check whether the current element of the array is an object with class2 property or tutor property.
$.each(raw00.allData, function(index, entry) {
if (entry.hasOwnProperty('class2')) {
$.each(entry.class2, function (index, data)
{
console.log(this.name);
test += '<tr><td>'+this.name+'</td>';
});
}
if (entry.hasOwnProperty('tutor')) {
$.each(entry.tutor, function (index, data)
{
console.log(this.fname);
test += '<td>'+this.fname+'</td></tr>';
});
}
$('#all-courses-table-content').html( test );
});
Things would probably be simpler if you redesigned the data structure. It generally doesn't make sense to have an array of objects when each object just has a single key and it's different for each. I suggest you replace the allData array with a single object, like this:
var raw00 = {
"allData": {
"class2": [
{
"tid": "1",
"name": "Monday 2"
},
{
"tid": "1",
"name": "Monday Test"
}
],
"tutor": [
{
"fname": "Jeffrey",
"lname": "Kranenburg"
},
{
"fname": "Jeffrey",
"lname": "Kranenburg"
}
]
}
};

Categories

Resources