Loop through a json multidimensional array in javascript - javascript

i need some help about json multidimensional array
"00100": {
"claim_id": "21",
"reference_no": "00100",
"distributor_name": "Standard Match",
"group_name": "A",
"month": "Jun2017",
"grand_total": "268.532",
"details": [
{
"product_name": "Match Type 1",
"price": "102.00",
"quantity": "02",
"net_amount": "179.52"
},
{
"product_name": "Match type 2",
"price": "101.15",
"quantity": "01",
"net_amount": "89.012"
}
]
}
Please explain me how to create a loop for this having a nested arrays!
enter image description here

You can get all nested properties like below:
$.each(dataArray, function (i) {
$.each(this, function (key, value) {
{
//base properties
alert(key + " : " + value);
if (key == "details") {
$.each(value, function (key1, value1) {
//child properties
for(k in value1) {
alert( key1 + ':' + k + ':' + value1[k]);
}
})
}
}
});
});

Use the below code to bind the array to the datatable.
$(document).ready(function() {
var data = {"00100":{"claim_id":"21","reference_no":"00100","distributor_name": "Standard Match","group_name": "A","month": "Jun2017","grand_total": "268.532","details":[{ "product_name": "Match Type 1","price": "102.00","quantity": "02","net_amount": "179.52"},{"product_name": "Match type 2","price": "101.15","quantity": "01","net_amount": "89.012"}]}};
var table = $("#tbl");
table.DataTable ({
"data" : data['00100']['details'],
"columns" : [
{ "data": "product_name" },
{ "data": "price" },
{ "data": "quantity" },
{ "data": "net_amount" }
]
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="tbl" class="display" width="100%">
<thead>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Amount</th>
</tr>
</thead>
</table>

Related

Crossmatch two JSON files with the same values but different name to make a table from the two

I want to create a table build from two different JSON files. One of them shows me the names, work position, and age. The other shows me emails, name and also their work occupation. However, they have different names for the same values and are in different order. I used mustache.js to render the data, but I noticed the files have different order, so the names did not match the emails, as I build my table from fetching the two different files.
var text = '[
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
]'
var text2 = '[
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
]'
var obj = JSON.parse(text);
$(document).ready(function() {
var template = $('#user-template').html();
for(var i in obj)
{
var info = Mustache.render(template, obj[i]);
$('#ModuleUserTable').html(info);
}
});
var obj2 = JSON.parse(text2);
$(document).ready(function() {
var template2 = $('#user-template2').html();
for(var i in obj2)
{
var info = Mustache.render(template2, obj2[i]);
$('#ModuleUserTable2').html(info);
}
});
<table border="1" id = "ModuleUserTable">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Age</th>
</tr>
</table>
<script id="user-template" type="text/template">
<tr>
<td>{{name}}</td>
<td>{{occupation}}</td>
<td>{{age}}</td>
</tr>
</script>
<table border="1" id = "ModuleUserTable2">
<tr>
<th>FullName</th>
<th>Work</th>
<th>Email</th>
</tr>
</table>
<script id="user-template2" type="text/template">
<tr>
<td>{{id}}</td>
<td>{{position}}</td>
<td>{{Email}}</td>
</tr>
</script>
I want to combine the data, so I can have all values in one table. So I have name, age, work, and email in one. I also have a 3rd Json from witch I can get their names only, but in the file the name of it is also different and it is only the value that is the same so it looks like "user135":"Jeff". I was thinking of doing something like this, but I do not know how to do it right:
function(nameuser)
for (var name) {
if(name."user135 == "Jeff"){
jQuery( Mustache.render($('#ModuleUserTable').html(), name)).appendTo("#ModuleUserTable2");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
This code will complete the first list items from second list via matching id and name properties. You can explore the result situation of list1 inside of the table;
var list1 = [
{
"occupation": "SV",
"name": "Mark",
"age":21
},
{
"occupation": "PE",
"name": "Jeff",
"age":24
},
{
"occupation": "MH",
"name": "Steven",
"age":20
},
{
"occupation": "GP",
"name": "Briana",
"age":22
}
];
var list2 = [
{
"position": "PE",
"id": "Jeff",
"Email":"jeff#gmail.com"
},
{
"position": "SV",
"id": "Mark",
"Email":"mark#gmail.com"
},
{
"position": "GP",
"id": "Briana",
"Email":"briana#gmail.com"
},
{
"position": "MH",
"id": "Steven",
"Email":"steven#gmail.com"
}
];
function findSource(name){
let temp = null;
$(list2).each((index,object)=>(temp==null && object.id == name) ? temp=object : 0);
return temp;
}
function complete(object){
let source = findSource(object.name);
if(source!=null&&source!=undefined){
object.position = source.position;
object.Email = source.Email;
}
}
function addToTable(object){
let tr= $("<tr>");
$(tr).append("<td>" + object.occupation + "</td>");
$(tr).append("<td>" + object.name + "</td>");
$(tr).append("<td>" + object.age + "</td>");
$(tr).append("<td>" + object.position + "</td>");
$(tr).append("<td>" + object.Email + "</td>");
$("#ModuleUserTable2").append(tr);
}
$(list1).each((index,item)=>{
complete(item);
addToTable(item);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" id = "ModuleUserTable2">
</table>

How can I do any multiplication or any mathematical operation for 2 rows in data table

I am new to development, and trying to build data table with JSON. So far I did
{
"qty": "2",
"price": 1
}, {
"qty": "3",
"price": "5",
}, {
"qty": "3",
"price": "4",
}
var table = $('#example').DataTable({
data: dataSet,
columns: [{
title: "qty",
data: "qty"
},
{
title: "price",
data: "price",
render: function(data, type, row) {
return '<input type="number" value="' + data + '">';
},
{
title: "total",
data: "multiplication'}
}
]
I want to perform multiplication of two rows qty and price and store result in third row.
Consider another example.
$(function() {
var dataSet = [{
"qty": 2,
"price": 1.00,
},
{
"qty": 3,
"price": 5.99
},
{
"qty": 3,
"price": 4.00
}
];
function calcTotal(q, p) {
var t = 0.00;
t = parseInt(q) * parseFloat(p);
return t.toFixed(2);
}
$.each(dataSet, function(i, r) {
r.total = calcTotal(r.qty, r.price);
});
var table = $('#example').DataTable({
data: dataSet,
columns: [{
"data": "qty"
},
{
"data": "price",
"render": function(data, type, row) {
return '$<input type="number" class="price-input" min="0.00" step="0.01" value="' + data + '" />';
}
},
{
"data": "total",
"render": function(data, type, row) {
return "$" + data;
}
}
]
});
$("#example").on("change", ".price-input", function(event) {
var row = $(this).closest("tr");
var qty = table.cell($("td", row).eq(0)).data();
var price = $(this).val();
var total = table.cell($("td", row).eq(2).get(0));
total.data(calcTotal(qty, price)).draw();
});
});
td {
text-align: center !important;
}
.price-input {
width: 5em;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css" />
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
This updates the Data Set before building the Table. So the values are already there. You can then use a change callback to modify that data.
Note: Most interfaces want to change the Quantity and not the price, but since your example changed the Price, I kept it as is. You can easily modify this to work the other way.
Here is a simple solution you can do this with columnDefs option:
In your column definition, add a third data column with the value null. (Remember to have the number of columns matching in your HTML). I created a third HTML column with the <th>Total</th>. The table will render the column empty.
When it gets to the columnDef, you want to make sure you target the correct column, remember it reads them based on a 0 index, so 2 is actually 3.
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return type === 'display' ? ((full.qty)*(full.price)) + '' : data;
}
Remember, the full parameter is the data for the entire row, so in the return of your render, you multiply the two data values (full.qty)*(full.price)
var dataSet = [
{
"qty": "2",
"price": "1",
},
{
"qty": "3",
"price": "5"
},
{
"qty": "3",
"price": "4"
}]
var table = $('#example').DataTable({
data: dataSet,
columns: [
{"data" : "qty"},
{"data": "price"},
{"data" : null}
],
columnDefs: [{
"targets": 2,
"render": function(data, type, full, meta) {
return "$" + ((full.qty)*(full.price));
}
}]
});
td {
text-align: center !important;
}
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"/>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.dataTables.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Issue Looping through an array of Objects dynamically using Javascript

Working on a Laravel application whereby am fetching data from the frontend and populating
dynamically on the frontend using Javascript. On the frontend I have partitioned in 2 major columns (left column and right column). On the left column there is a link which when hovered over or clicked the respective policies display on the right side.
The problem is am finding it quite difficult to iterate the policies array which contains a collection of Javascript objects and display them dynamically in the table.
When I use the method below I get [object Object] in the table body
asm variable from the backend
"agency_sales": [
{
"id": "111",
"policies": [
{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
},
]
}
{
"id": "222",
"policies": [
{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
},
]
}
]
Left column containing the link with a dynamic id
<div class="col-md-4">
#foreach($asm as $a)
Agency Sales Managers ID : {{ $a['id'] }}
#endforeach
</div>
Right column containing the table I would like to populate dynamically
<div class="col-md-8">
<table class="table table-hover mg-b-0 tx-11" id="summary-table">
<thead>
<tr>
<th>NAME</th>
<th>SUM</th>
<th>DATE</th>
</tr>
</thead>
<tbody>
<tr> <!-- Add policies dynamically via JS under respective thead columns--></tr>
</tbody>
</table>
</div>
JavaScript Code
$( document ).ready(function() {
var asmData = {!! json_encode($asm) !!};
});
$(document).on("mouseenter", "a", function() {
//Make sure table is empty
$('#summary-table tbody tr').html('');
//Execute ASM
var asmPolicies = '';
//Fetch id of a tag in the DOM
var asmId = $(this).attr('id');
for(var i = 0; i < asmData.length; i++) {
if(asmId == asmData[i]['id']) {
for(var j = 0; j < asmData[i]['policies'].length; j++){
asmPolicies += '<tr><td>' + asmData[i]['policies'][j] + '</td></tr>';
}
}
}
//append asmPolicies Html to the table
$('#summary-table tbody tr').append(asmPolicies);
//END ASM
});
Several issues - the main ones are
faulty JSON
not parsing the object
appending trs to trs instead of the tbody
Note the use of data attribute on the link
const asmData = [{
"id": "111",
"policies": [{
"name": "JOHN DOE 1",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 2",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
}
]
}, {
"id": "222",
"policies": [{
"name": "JOHN DOE 3",
"sum_covered": "555000",
"date": "2018-05-16 12:02:32"
},
{
"name": "JOHN DOE 4",
"sum_covered": "404000",
"date": "2018-02-20 17:33:25"
}
]
}]
$(document).on("mouseenter", "a", function() {
var $tb = $('#summary-table tbody');
//Make sure table is empty
$tb.empty()
var asmId = $(this).attr('data-id'),
asmPolicies = "";
for (var i = 0; i < asmData.length; i++) {
if (asmId == asmData[i]['id']) {
for (var j = 0; j < asmData[i]['policies'].length; j++) {
var pol = asmData[i]['policies'][j];
asmPolicies += '<tr><td>' + pol.name + '</td><td>' + pol.sum_covered + '</td><td>' + pol.date + '</td><td>' + '</td></tr>';
}
}
}
//append asmPolicies Html to the table
$tb.append(asmPolicies);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
111 | 222
<div class="col-md-8">
<table class="table table-hover mg-b-0 tx-11" id="summary-table">
<thead>
<tr>
<th>NAME</th>
<th>SUM</th>
<th>DATE</th>
</tr>
</thead>
<tbody>
<tr>
<!-- Add policies dynamically via JS under respective thead columns-->
</tr>
</tbody>
</table>
</div>

Trying to parse JSON objects to HTML table

I am using a jquery method to load JSON objects from the database. Then, I would want to display the record row by row in a HTML table. As can be seen in my JS file, I have tried to use a for and for each loop to loop through the data records but none of them are working apparently. My table seems to not display anything on the table or even error on result/ console log. However, there are data in my network log.
The json record in the network log is:
data: [
0:{
"id": "1",
"name": "John",
"type": "Client"
},
1:{
"id": "2",
"name": "Damen",
"type": "Agent"
},
2:{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
The HTML page is:
<table id="report" class="table table-bordered table-striped table-hover js-basic-example dataTable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script>
app.viewReport();
</script>
My JS page is:
viewReport : function() {
$.ajax({
url: "/FIS/back-api/client/transaction/view",
dataType: "json",
method : 'GET',
success : function(data){
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].id+ "</td>");
tr.append("<td>" + data[i].name+ "</td>");
tr.append("<td>" + data[i].type+ "</td>");
$('#report tbody').append(tr);
}
}
/*$.each(data,function(i,item){
$('#report tr.odd').remove();
$("#report tbody").append(
"<tr>"
+"<td>"+item.id+"</td>"
+"<td>"+item.name+"</td>"
+"<td>"+item.type+"</td>"
+"</tr>" )
})
}*/
})
},
John , your JSON is invalid , this is the closest valid JSON i prepared from sample you shared above :
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
Notice that for an array of objects 0 : {} format is invalid, so when you query it in a loop you're not receiving any result.
Incorrect :
0:{
"id": "1",
"name": "John",
"type": "Client"
}
Correct :
{
"id": "1",
"name": "John",
"type": "Client"
}
How to validate your JSON
Following sites will help you verify your json :
jsonlint
jsoneditoronline
Answer
Re-generate your JSON and then proceed as indicated in other answers.
Also , i would advice against parsing the result as string ! In my humble opinion, the proper way to do this is to return a valid json from Backend/server
Your data array is having keys, which is incorrect json format, If its an array it should look like:
[
{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
]
Process your JSON data correctly like Winnie said in another answer of this question. Then you have not defined table row correctly.
for (i = 0; i < data.length; i++) {
$('#report tbody').append(
$('<tr>').append(
$('<td>').text(data[i].id),
$('<td>').text(data[i].name),
$('<td>').text(data[i].type)
)
);
}
try to append it like this
for (var i = 0; i < data.length; i++) {
var htm = '';
htm += '<tr>';
htm += "<td>" + data[i].id.toString() + "</td>";
htm += "<td>" + data[i].name.toString() + "</td>";
htm += "<td>" + data[i].type.toString() + "</td>";
htm += '</tr>';
$('#report tbody').append(htm);
}
var data = [{
"id": "1",
"name": "John",
"type": "Client"
},
{
"id": "2",
"name": "Damen",
"type": "Agent"
},
{
"id": "3",
"name": "Aiden",
"type": "Admin"
}
];
for (var i = 0; i < data.length; i++) {
var body = document.getElementById("tableBody");
var row = body.insertRow();
for (var item in data[i]) {
var cell = row.insertCell();
cell.innerHTML = data[i][item];
}
}
<html>
<body>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
</body>
</html>

Javascript Datatables generating HTML link using render function on JSON data

I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );
Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/

Categories

Resources