guys i know its dummy question but i have spent alot of hours in this and still cant reach .. i want print the json content in table form .. here is my code
[{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}]
in javascript
$(document).ready(function() {
$.ajax({
url : 'data.json',
error : function(that, e) {
console.log(e);
},
success : function(data) {
$.each(data, function(index1, MyList) {
$.each(MyList, function(index2, item) {
$('body').append('<div id="div'+ index2+'" />');
$('#div' + index2).append(MyList[index2]);
});
});
}
});
});
here is my output
1234
name1name2name3name4
67305917
feedback1feedback2feedback3feedback4
and i want to make it in table form like this
1 name1 67 feedback1
2 name2 39 feedback2
3 name3 59 feedback3
4 name4 17 feedback4
try this snippet.you dont need two loops. just loop on items and build the bale row markup with data in each item.
data = [{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}]
var table_markyp = "<table>";
$.each(data, function(i, v) {
table_markyp += '<tr><td>' + v.id + '</td><td>' + v.name + '</td><td>' + v.age + '</td><td>' + v.feedback + '</td><tr>';
})
table_markyp += '</table>';
$('body').append(table_markyp)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
what you can do is , you have to create and HTML structure,
so that all the result will be displayed with a line by line and for that you can follow the table structure,.
check this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "data.json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
var Mytable = "<table>";
$.each(data, function(temp, res) {
Mytable +=
'<tr>\n\
<td>' + res.id + '</td>\n\
<td>' + res.name + '</td>\n\
<td>' + res.age + '</td>\n\
<td>' + res.feedback + '</td>\n\
<tr>';
});
Mytable += '</table>';
$('body').append(Mytable);
}
});
});
</script>
</html>
create a container with an id e.g <div id="tablecontainer"> and this below will generate a table with the results
if you want headers you can take one object from data e.g data[0], perform Object.keys(data[0]) and attached them to a <tr/> <th/> object like the row method below
success: function(data) {
var container = $('#tablecontainer');
var table = $('<table></table>');
data.forEach(function(datarow) {
var row = $("<tr />");
for (var item in datarow) {
row.append($("<td>" + datarow[item] + "</td>"));
}
table.append(row);
});
container.append(table);
}
example output with headers:
var data = [{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}];
var container = $('body');
var table = $('<table></table>');
var head = $("<tr />");
var keys = Object.keys(data[0]);
keys.forEach(function(key){
head.append($("<th>" + key + "</th>"))
})
table.append(head);
data.forEach(function(datarow) {
var row = $("<tr />");
for (var item in datarow) {
row.append($("<td>" + datarow[item] + "</td>"));
}
table.append(row);
});
container.append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There is a JavaScript object and I need to retrieve free_time, done_ratio, criticalTask, dependency for each task element.
This is what i have done, but it doesn't work.
var mock_data_allocation = {"allocation":[{"id":7,"name":"Manoj D","limit":4.0,"available_time":16.0,"tasks":[{"id":34,"name":"issue_25","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":3,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[]},{"id":36,"name":"issue_27","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":3,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[33,34]},{"id":38,"name":"issue_29","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":5,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[35,36]},{"id":39,"name":"issue_30","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":4,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[37,38]}]},{"id":5,"name":"Thisun H","limit":4.0,"available_time":16.0,"tasks":[{"id":33,"name":"issue_24","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":5,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[]},{"id":35,"name":"issue_26","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":2,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[]},{"id":37,"name":"issue_28","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":6,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[34]}]}]};
$(mock_data_allocation.allocation).each( function(i, value){
$('.taskdetail').append('<tr>' +
'<td>'+ (i+1) +'</td>'+
'<td>'+ value.tasks.name +'</td>'+
'<td>'+value.tasks.free_time+'</td>'+
'<td>'+value.tasks.done_ratio+'</td>'+
'<td>'+value.tasks.criticalTask+'</td>'+
'<td>'+value.tasks.dependency.length+'</td>'+
'</tr>');
});
<tbody class="taskdetail"></tbody>
Currently the output is:
1 undefined undefined 0 true 0
2 undefined undefined 0 false 0
The tasks property of the value objects is an array of objects but your code assumes that it's an object. Your code fails as the tasks array doesn't have dependency property and subsequently value.tasks.dependency.length fails as value.tasks.dependency returns undefined and undefined doesn't have length property.
You should either get a specific element from the tasks array:
.append('<tr>' +
'<td>'+ (i+1) +'</td>'+
'<td>'+ value.tasks[0].name +'</td>'+
'<td>'+value.tasks[0].free_time+'</td>'+
'<td>'+value.tasks[0].done_ratio+'</td>'+
'<td>'+value.tasks[0].criticalTask+'</td>'+
'<td>'+value.tasks[0].dependency.length+'</td>'+
'</tr>');
or iterate through it:
var $target = $('.taskdetail');
$.each(mock_data_allocation.allocation, function(i, value) {
$.each(value.tasks, function(ii, task) {
$target.append('<tr>' +
'<td>'+ (ii+1) +'</td>'+
'<td>'+ task.name +'</td>'+
'<td>'+task.free_time+'</td>'+
'<td>'+task.done_ratio+'</td>'+
'<td>'+task.criticalTask+'</td>'+
'<td>'+task.dependency.length+'</td>'+
'</tr>');
});
});
Also you should not create a jQuery object by passing a regular object to jQuery. Use the $.each utility function instead.
You should try this....
$.each(mock_data_allocation.allocation,function(i, value){
$.each(value.tasks,function(j,val){
$('.taskdetail').append('<tr>' +
'<td>'+ (j+1) +'</td>'+
'<td>'+ val.name +'</td>'+
'<td>'+val.free_time+'</td>'+
'<td>'+val.done_ratio+'</td>'+
'<td>'+val.criticalTask+'</td>'+
'<td>'+val.dependency.length+'</td>'+
'</tr>');
});
});
$(mock_data_allocation.allocation) is nothing, in fact $(mock_data_allocation) is nothing.
You may want jQuery.each( mock_data_allocation.allocation, function ... ?
Many answers here point a main issue, which is the way the object is explored,and I agree.
But I don't understand why there is no answer pointing another issue: the needed result comes from two different levels in the original object.
At the task level are the informations name, done_ratio, and criticalTask.
But it's one level up that resides free_time (in fact named available_time), which is the same for all tasks (note #2 in the code below).
The same applies for the 1st <td>, which includes a counter: this one might be computed either globally or at the tasks level (note #1 in the code below).
Here is a really working solution (see this fiddle):
var all = mock_data_allocation.allocation;
for (var i = 0, n = all.length; i < n; i++) {
var availTime = all[i].available_time,
tasks = all[i].tasks;
for (var j = 0, m = tasks.length; j < m; j++) {
var task = tasks[j];
$('.taskdetail').append(
'<tr>' +
'<td>' + (i + 1) + '-' + (j + 1) +'</td>'+ // <-- #1
'<td>' + task.name + '</td>' +
'<td>' + availTime + '</td>' + // <-- #2
'<td>' + task.done_ratio + '</td>' +
'<td>' + task.criticalTask + '</td>' +
'<td>' + task.dependency.length + '</td>'+
'</tr>'
);
}
}
It seems to me that you must unpack the tasks array
var mock_data_allocation = {
"allocation": [{
"id": 7,
"name": "Manoj D",
"limit": 4.0,
"available_time": 16.0,
"tasks": [{
"id": 34,
"name": "issue_25",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 3,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": []
}, {
"id": 36,
"name": "issue_27",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 3,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [33, 34]
}, {
"id": 38,
"name": "issue_29",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 5,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [35, 36]
}, {
"id": 39,
"name": "issue_30",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 4,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [37, 38]
}]
}, {
"id": 5,
"name": "Thisun H",
"limit": 4.0,
"available_time": 16.0,
"tasks": [{
"id": 33,
"name": "issue_24",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 5,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": []
}, {
"id": 35,
"name": "issue_26",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 2,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": []
}, {
"id": 37,
"name": "issue_28",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 6,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": [34]
}]
}]
};
$(mock_data_allocation.allocation).each(function(i, value) {
$(value.tasks).each(function(index, el) {
$('.taskdetail').append('<tr>' +
'<td>' + (i + 1) + '</td>' +
'<td>' + el.name + '</td>' +
'<td>' + el.free_time + '</td>' +
'<td>' + el.done_ratio + '</td>' +
'<td>' + el.criticalTask + '</td>' +
'<td>' + el.dependency.length + '</td>' +
'</tr>');
});
});
https://jsfiddle.net/
Your problem lies in the use of $(mock_data_allocation.allocation).each There are two different .each functions in JQuery
$(selector).each() - Used to Iterate over a jQuery object
and
jQuery.each() - A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
mock_data_allocation is not a DOM element and so trying to make it into a JQuery object with $(mock_data_allocation.allocation) fails because mock_data_allocation.allocation is not a DOM element.
You need to iterate over a data object so instead of
$(mock_data_allocation.allocation).each( function(i, value){...
you should be doing
$.each(mock_data_allocation.allocation, function(i, value){...
That will cure the 'undefined' problem.
I've some json files included in the page like this:
<script type="text/javascript" language="javascript" src="json/divaniModerni.json"></script>
<script type="text/javascript" language="javascript" src="json/divaniClassici.json"></script>
All of them having same structure, containing different elements:
var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
},
]
}
I'm now able to parse the file like this:
$(divaniModerni.modelli).each(function(index, element){ (...) }
but it's possible to dinamically change the file to parse passing the name to a function, like this?
function show(category)
{
$(category.modelli).each(function(index, element){ (...) }
}
show(divaniModerni);
I've tried with:
$(window[category].modelli).each(function(index, element){ (...) }
but It's not working...
EDIT:
Inside the each I'm dinamically creating a row on a table, based on the selected json elements:
$(divaniModerni.modelli).each(function(index, element){
if (i == 1)
riga += "<tr>";
riga += "<td><figure><a class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + ".jpg'><img src='images/anteprima/divani/" + element.nome + ".jpg' alt='" + element.nome + "'></a><div class='descrizione'>" + element.nome;
if (element.num > 0)
{
for (j = 2; j <= element.num; j++)
{
riga += "<a style='display:none;' class='anteprime' rel='prettyPhoto[gallery" + i + "]' href='images/divani/" + element.nome + j + ".jpg'><img src='images/anteprima/divani/" + element.nome + j + ".jpg' alt='" + element.nome + "'></a>";
}
}
riga += "</div></figure></td>";
if (i == categoria.modelli.length)
{
riga += "</tr>";
$('#mostra').append(riga);
}
else if (i % 4 == 0)
{
riga += "</tr>";
$('#mostra').append(riga);
riga = "<tr>";
}
i++
})
Pass in the object reference directly into the each statement to only iterate on that.
http://jsfiddle.net/b3zdahc0/
var divaniModerni = {
"modelli": [
{
"nome": "California",
"num": "5",
},
{
"nome": "Terra",
"num": "6",
},
{
"nome": "Laura",
"num": "7",
},
{
"nome": "Nonstop",
"num": "11",
},
{
"nome": "Venere",
"num": "8",
},
{
"nome": "Comfort",
"num": "5",
},
{
"nome": "Infinity",
"num": "8",
}
]
};
function show(category)
{
$.each(category.modelli, function(index, element) {
alert(index)
});
}
$("button").on("click", function(e) {
show(divaniModerni);
});
I'm building a HTML table using JSON to populate it.
Here's the JSON:
{
"grid": {
"name": "JsonGrid",
"columns": [
{
"name": "ID",
"width": "100px"
},
{
"name": "Name",
"width": "100%"
},
{
"name": "Departments",
"width": "250px"
},
{
"name": "Locations",
"width": "250px"
}
]
},
"data": [
{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
},
{
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
},
{
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}
]
}
and the function that loops through the data object:
function addDataFromJson(json)
{
var data = json.data;
for(var i=0;i<data.length;i++) // for each row
{
var columns = '';
for(var b=0;b<Object.keys(data[i]).length;b++) // for each column
{
var content = data[i][b];
console.log(content);
columns += '<td>'+content+'</td>';
}
var row = columns;
$( '<tr>' + row + '</tr>' ).appendTo('.uiGridContent tbody').hide().fadeIn();
}
}
So I loop through to get the rows and look inside to find what columns I need, and then try and put the data into each column and then append the row. The columns and rows are perfect, but the data never gets pulled out!
It looks like I'm getting confused as I step into the second loop that pulls the actual data for each column. What should the content variable contain? Taking into consideration that sometimes the content may contain arrays instead of just strings.
The problem is the use of b, it is just an index of the key not the actual property key so you need
var content = data[i][Object.keys(data[i])[b]];
like
var json = {
"grid": {
"name": "JsonGrid",
"columns": [{
"name": "ID",
"width": "100px"
}, {
"name": "Name",
"width": "100%"
}, {
"name": "Departments",
"width": "250px"
}, {
"name": "Locations",
"width": "250px"
}]
},
"data": [{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, {
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}, {
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}]
};
function addDataFromJson(json) {
var data = json.data;
for (var i = 0; i < data.length; i++) // for each row
{
var columns = '',
keys = Object.keys(data[i]);
for (var b = 0; b < keys.length; b++) // for each column
{
var content = data[i][keys[b]];
console.log(content);
columns += '<td>' + content + '</td>';
}
var row = columns;
$('<tr>' + row + '</tr>').appendTo('.uiGridContent tbody').hide().fadeIn();
}
}
addDataFromJson(json)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="uiGridContent">
<tbody></tbody>
</table>
A more simpler way will be
var json = {
"grid": {
"name": "JsonGrid",
"columns": [{
"name": "ID",
"width": "100px"
}, {
"name": "Name",
"width": "100%"
}, {
"name": "Departments",
"width": "250px"
}, {
"name": "Locations",
"width": "250px"
}]
},
"data": [{
"id": 1,
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, {
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}, {
"id": 3,
"name": "Company C",
"departments": [
"Medical",
"Family",
"Criminal"
],
"locations": [
"Sheffield",
"Rotherham"
]
}]
};
function addDataFromJson(json) {
var data = json.data;
var rows = $.map(data, function(record) {
var cols = $.map(record, function(value, key) {
return '<td>' + value + '</td>';
})
return '<tr>' + cols + '</tr>';
})
$(rows.join('')).hide().appendTo('.uiGridContent tbody').fadeIn();
}
addDataFromJson(json)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="uiGridContent">
<tbody></tbody>
</table>
Better use ECMAScript 5.1 helpers for better understanding what your code makes:
function addDataFromJSON(json) {
//just check that data is array
var data = json && Array.isArray(json.data) ? json.data : [];
data.forEach(function(rowObject) {
//every loop will create a row
var tr = document.createElement('tr');
Object.keys(rowObject).forEach(function(cellKey) {
//every loop will create a cell
var td = document.createElement('td');
td.innerText = rowObject[cellKey];
tr.appendChild(td);
});
table.appendChild(tr);
});
}
var table = document.querySelector('#table');
var jsonData = {
"data": [{ //this is row
"id": 1, // this is a cell value
"name": "Company A",
"departments": [
"Software",
"Recruitment",
"Consulting"
],
"locations": [
"Sheffield",
"Rotherham",
"London",
"New York"
]
}, { //this is one more row
"id": 2,
"name": "Company B",
"departments": "",
"locations": [
"Hillsborough",
"City Centre",
"Crystal Peaks"
]
}]
};
function addDataFromJSON(json) {
//just check that data is array
var data = json && Array.isArray(json.data) ? json.data : [];
data.forEach(function(rowObject) {
//every loop will create a row
var tr = document.createElement('tr');
Object.keys(rowObject).forEach(function(cellKey) {
//every loop will create a cell
var td = document.createElement('td');
td.innerText = rowObject[cellKey];
tr.appendChild(td);
});
table.appendChild(tr);
});
}
addDataFromJSON(jsonData);
table,
td {
border: 1px solid #ccc;
border-spacing: 0;
border-collapse: collapse;
}
td {
padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table id=table></table>
</body>
</html>