How can I output JSON data to an HTML table? - javascript

I have some data which is being filtered in the code below. The filter works well. I've added an 'onclick' function to a button in my HTML and my data shows on screen no problem, but what I would like is when I click the button, It shows a table with the filtered data in it, and a way to exit the table, either by a box closing or click the button again and it disappears. I don't mind which.
function loadPRFilter(){
var surgerySearchTerm = "pr";
var data = jsonArray.filter(jsonObject => jsonObject.surgeryType.includes(surgerySearchTerm));
var mainContainer = document.getElementById("pr");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Name: ' + data[i].name + ' ' +'Score: '+ data[i].score + ' '+ 'Severity:'+' '+ data[i].severity;
mainContainer.appendChild(div);
console.log("Filtered pr");
console.log(data);
}
};
here is my data:
var jsonArray =[
{
"ID": 1 ,
"name": "sub conjunctival haemorrhage",
"score" : 1,
"surgeryType": ["scleral buckle"] ,
"severity" : "mild"
},
{
"ID": 2,
"name": "dry eye",
"score": 5,
"surgeryType":[ "pr" ],
"severity" : "moderate"
},
{
"ID": 3,
"name": "ha's",
"score": 5,
"surgeryType":["general", "scleral buckle", "ppv", "pr"],
"severity" : "moderate"
}

Related

How to display all fields of a nested json in table format using Bootstrap

I want to write a utility which connects to a REST api downloads data in JSON format and then paints the data as nested tables using Bootstrap.
JSON Data -
[
{
"id" : "Id1",
"name" : "Name1",
"orders" : [{"orderId" : "o1", "size" : 34}, {"orderId" : "o2", "size" : 3}]
},
{
"id" : "Id2",
"name" : "Name2",
"orders" : [
{"orderId" : "o3", "size" : 5, "addresses" : [{"addressId" : "a1", "phone" : "1235"}, {"addressId" : "a2", "phone" : 555}]},
{"orderId" : "o4", "size" : 5, "addresses" : [{"addressId" : "a3", "phone" : "1235"}]}
]
}
]
I looked at the sub-table feature of Bootstrap, however it seems that it would need lot of custom code to get this working. Is there a better way to bind the json to table in a generic way?
Edit
After spending some time I was able to achieve this -
As you can see, I could get one level of nesting, however i just need to go one level deep. Any suggestions?
<script>
var $table = $('#table')
function buildTable($el, jsonData) {
var i; var j; var row
var columns = []
var data = []
if(!Array.isArray(jsonData) && jsonData.length == 0) {
return;
}
Object.keys(jsonData[0]).forEach( (k) => {
columns.push({
field: k,
title: k,
sortable: true
})
})
for(var j = 0; j < jsonData.length; j++) {
row = {}
Object.keys(jsonData[j]).forEach( (k) => {
row[k] = jsonData[j][k]
})
data.push(row)
}
$el.bootstrapTable({
columns: columns,
data: data,
detailFilter: function (index, row) {
console.log("detail filter " + Object.values(row))
for(var k in row) {
if(Array.isArray(row[k])){
return true;
}
}
return false;
},
onExpandRow: function (index, row, $detail) {
console.log("expand row keys " + Object.keys(row))
console.log("expand row vals " + Object.values(row))
var newRow = {};
for(var k in row) {
if(Array.isArray(row[k])){
alert('found ' + row[k])
newRow = row[k]
break
}
}
buildTable($detail.html('<table></table>').find('table'), newRow)
}
})
};
var mydata =
[
{
"id": 0,
"name": "test0",
"price": "$0",
"orders" :
[
{
"name" : "ABC",
"size" : 25,
"someList": [{"a":1, "b":2}, {"a":3, "b":4}]
},
{
"name" : "XYZ",
"size" : 50
}
]
}
/* {
"id": 1,
"name": "test1",
"price": "$1"
},
{
"id": 2,
"name": "test2",
"price": "$2",
"orders" : [{"name" : "def", "size": 45}]
}*/
];
$(function() {
buildTable($table, mydata)
})

How to loop through jason data and display it in data list tag (dl)

I'm trying to loop through some JSON data (var mydata) and mydata is an array of two elements, the second element in the array
mydata[1] is a multidimensional array, I need to display the first element i.e mydata[0] in a dt and display elements from mydata[1] in a dd within that.
I tried every option but I'm really stuck and I need any help on this. Below is my code:
var mydata = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
function getCategories(id){
$.ajax({
url: '{$getcatUrl}',
type: 'POST',
data: {category_id: id},
success: function (data) {
data = jQuery.parseJSON(data);
//console.log(data); return;
if(data.length > 0){
firstdata = data[0];
secdata = data[1];
for(var i = 0; i < firstdata.length; i++) {
level_1 = firstdata[i].name;
level_1_id = firstdata[i].id;
for(var j = 0; j< secdata.length; j++){
if(secdata[i][j] !== undefined){
level_2='';
level_2 = secdata[i][j].name;
level_2_id = secdata[i][j].d;
}
console.log(level_2);
}
var dldata = $(
'<dl>'+
"<dt href='" + level_1_id + "'>" + level_1 + "</dt>"+
"<dd href='" + level_2_id + "'>" + level_2 + "</dd>"+
'</dl>'
);
}
}else{
console.log('no item for this categories');
}
},
error: function(jqXHR, errMsg) {
// handle error
console.log(errMsg);
}
});
}
The var level_1 and level_1_id works fine, but i keep getting error for variable level_2, the error says can't read property 'name' of undefined, any solution to this problem will be appreciated and am also open to new ideas about doing it better,
Essentially the problem is that you overwrite the level_1 and level_2 variables each time your for loops run. So by the time you get to the code which makes the HTML, they have been overwritten multiple times and only the last version remains, and you only print that once in any case.
This will resolve it - in this case by generating the HTML elements directly within each loop, although you could of course do it by appending to a variable and then outputting everything at the end, if that's your preference.
var data = [
[{
"id": "67",
"name": "Baby & Toddler Clothing "
}, {
"id": "68",
"name": "Kids' Clothing, Shoes & Accessories"
}, {
"id": "69",
"name": "Costumes, Reenactment Theater"
}],
[
[{
"id": "572",
"name": "Baby Clothing Accessories "
}, {
"id": "573",
"name": "Baby Shoes"
}],
[{
"id": "579",
"name": "Boys Clothing [Sizes 4 & Up] "
}, {
"id": "580",
"name": "Boys Shoes"
}],
[{
"id": "588",
"name": "Costumes"
}, {
"id": "589",
"name": "Reenactment & Theater "
}]
]
]
if (data.length > 0) {
var content = $("#content");
firstdata = data[0];
secdata = data[1];
for (var i = 0; i < firstdata.length; i++) {
var dl = $("#content").append("<dl/>");
dl.append("<dt href='" + firstdata[i].id + "'>" + firstdata[i].name + "</dd>");
for (var j = 0; j < secdata.length; j++) {
if (secdata[i][j] !== undefined) {
dl.append("<dd href='" + secdata[i][j].id + "'>" + secdata[i][j].name + "</dd>");
}
}
}
content.append(dl);
} else {
console.log('no item for this categories');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content"></div>

Angular: How to get the count of the Object with specific value?

I have a JSON database with objects. Each one has properties with a specific assigned value: a, b or c.
[
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
]
I want to display something like:
There is a total of 6 items: a x 3, b x 2 and c x 1.
I know I have to use objectsinmyjsondatabase.length to get the total.
I'm wondering how is it possible to get the length (number) of objects that have a specific value?
Define a function:
getCount(character) {
return this.objects.filter(obj => obj.category === character).length;
}
and the call it as:
this.getCount('a');
One way to solve your problem is to use map-reduce. Here is a quick solution. Hope that will solve your problem.
var data = [
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
];
// First get list of all categories
var categories = data.map(function(x) { return x["category"]; });
// Count no of items in each category
var countByCategories = categories.reduce(function(x, y) {
if (typeof x !== "object") {
var reduced = {};
reduced[x] = 1;
reduced[y] = 1;
return reduced;
}
x[y] = (x[y] || 0) + 1;
return x;
});
// Final build string that you want
var categoryStrings = [];
for (var category in countByCategories) {
categoryStrings.push(category + ' x ' + countByCategories[category]);
}
var msg = 'There is a total of ' + categories.length + ' items: ';
if (categoryStrings.length > 2) {
msg = categoryStrings.slice(0, -1).join(', ');
msg += ' and ' + categoryStrings.slice(-1);
} else {
msg = categoryStrings.join(', ');
}
// print results
console.log(msg);
You easily can count objects which have specific value like this
let objects = [
{
"id": 1,
"category": "a"
},
{
"id": 2,
"category": "b"
},
{
"id": 3,
"category": "c"
},
{
"id": 4,
"category": "a"
},
{
"id": 5,
"category": "a"
},
{
"id": 5,
"category": "b"
}
];
var filtered = new Array();
objects.filter(function (t) {
var found = filtered.some(function (el, index) {
if (false == (t.category === el.category)) {
return false;
}
filtered[index].count = filtered[index].count + 1;
return true;
}, filtered);
if (false === found) {
filtered.push({category: t.category, count: 1});
}
}, filtered);
console.log('There is a total of ' + objects.length + ' items: '
+ filtered.map(function (t) {
return t.category + ' x ' + t.count;
})
);

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

Multilevel list menu with JSON and jQuery Mobile

I try to reach following structure
a list of (distinct!) categories
Category 1
Category 2
Category n
And each Category links to the posts within the Category. And the posts link to the content
Post 1 Cat 1 --> Content Post 1 Cat 1
Post 2 Cat 2 --> Content Post 2 Cat 1
Question: I don't know how to create the distinct list of categories which leads to the posts. Any solutions?
This is my JSON example (this is from the json api plugin in wordpress)
{"status": "ok",
"count": 10,
"count_total": 20,
"pages": 2,
"posts": [
{
"id": 86,
"type": "post",
"slug": "inaktiviert",
"url": "http://localhost/wordpress/?p=86",
"status": "publish",
"title": "Post 1 Cat1",
"content": "his is content for Post1 Cat 1.",
"date": "2014-03-04 15:09:51",
"modified": "2014-03-04 15:09:51",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 84,
"type": "post",
"slug": "kann-nicht-aktualisiert-werden",
"url": "http://localhost/wordpress/?p=84",
"status": "publish",
"title": "Post 2 Cat1",
"content": "<p>This is content for Post2 Cat 1.</p>\n",
"date": "2014-03-04 15:09:25",
"modified": "2014-03-04 15:09:25",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 74,
"type": "post",
"slug": "dieses-symbol-zeigt-an",
"url": "http://localhost/wordpress/?p=74",
"status": "publish",
"title": "Post 1 Cat2",
"content": "This is Content for Post1 Cat 2",
"date": "2014-03-04 15:06:47",
"modified": "2014-03-04 15:06:47",
"categories": [
{
"id": 2,
"title": "Category 2",
"description": "",
"parent": 0,
"post_count": 3
}
],
}
]}
And this my JS
$(document).on("pagecreate", "#page1", function(){
var liste = $('#liste');
var AllListItems = '';
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
AllListItems += '<li>' + postTitle + '</li>';
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.empty().append(AllListItems).listview("refresh");
$("body").append(AllDynamicPages);
});
DEMO
I would approach it this way: Instead of a list, create a collapsible set where each child collapsible is a category, and each category collapsible contains a list of posts.
Here is your updated FIDDLE
So the top level HTML markup would be a collapsible set:
<div id="thelist" data-role="collapsibleset" data-theme="a" data-content-theme="a">
</div>
Then the code:
var liste = $('#thelist');
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
//see if we already have this category, if not create new collapsible
var $cat = $("#cat" + catid);
if ($cat.length == 0){
$cat = $('<div id="cat' + catid + '" data-role="collapsible"><h3>' + catTitle + '</h3><ul data-role="listview"></ul></div>');
liste.append($cat);
}
//create post link in category collapsible list
var postlink = '<li>' + postTitle + '</li>';
$cat.find("ul").append(postlink);
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.enhanceWithin();
$("body").append(AllDynamicPages);
It is the same iteration as you had before, but now for each category, we check if there is already a collapsible for that category. If there is not we create one and add it to the set. Then we create a link for the post and add it the list widget within the category collapsible.
Finally we call .enhanceWithin() to apply jQM styling.
The dynamic pages part stays exactly the same.

Categories

Resources