I want to make a mobile application using Cordova for my school homework project, and i need to fetch data from PHP Web Server, me already have JSON for this.
This is the example of my mobile app map :
http://prntscr.com/fhq63c .
This is the looks of my JSON :
Product Category :
[[
{"id":1,"name":"Product 1","created_at":"2017-06-06 08:31:34","updated_at":"2017-06-06 09:16:18"},
{"id":2,"name":"Product 2","created_at":"2017-06-06 09:16:12","updated_at":"2017-06-06 09:16:12"},
{"id":3,"name":"Product 3","created_at":"2017-06-06 09:16:24","updated_at":"2017-06-06 09:16:24"}
]]
Package Cateogry :
[[
{"id":1,"product_id":"1","name":"Package 1-1","jumlah_user":"1","created_at":"2017-06-06 09:34:11","updated_at":"2017-06-06 09:34:11"},
{"id":2,"product_id":"1","name":"Package 1-2","jumlah_user":"1","created_at":"2017-06-06 09:35:49","updated_at":"2017-06-06 10:03:43"},
{"id":3,"product_id":"2","name":"Package 2-1","jumlah_user":"1","created_at":"2017-06-07 03:03:35","updated_at":"2017-06-07 03:03:35"},
{"id":4,"product_id":"2","name":"Package 2-2","jumlah_user":"1","created_at":"2017-06-07 03:30:11","updated_at":"2017-06-07 03:30:11"},
{"id":5,"product_id":"3","name":"Package 3-1","jumlah_user":"12","created_at":"2017-06-07 03:31:36","updated_at":"2017-06-07 03:31:36"},
]]
List Price
[[
{"id":1,"package_id":"1","harga":"700000.00","masa_training":"2 x 1 jam","masa_maintenance":"2 bulan","tanggal_efektif":"2018-01-01","created_at":"2017-06-07 03:45:20","updated_at":"2017-06-07 03:45:20"},
{"id":2,"package_id":"2","harga":"500000.00","masa_training":"500","masa_maintenance":"100","tanggal_efektif":"2019-01-01","created_at":"2017-06-07 03:48:23","updated_at":"2017-06-07 03:48:23"},
{"id":3,"package_id":"3","harga":"50000.00","masa_training":"10","masa_maintenance":"20","tanggal_efektif":"2017-11-30","created_at":"2017-06-08 23:11:49","updated_at":"2017-06-08 23:11:49"}
]]
and this is how my menu will looks :
<ul class="list-group">
<li class="btn btn-lg btn-default list-group-item btn-menu">
<p class="productid" hidden>1</p>
<p class="productname">Product Name</p>
</li>
<li class="btn btn-lg btn-default list-group-item btn-menu">
<p class="productid" hidden>1</p>
<p class="productname">Product Name</p>
</li>
<li class="btn btn-lg btn-default list-group-item btn-menu">
<p class="productid" hidden>1</p>
<p class="productname">Product Name</p>
</li>
</ul>
```
and each button directly go to price list that connected to the product category.
Anyone have idea and can solved mine? thanks.
Assuming we have the json data stored in its corresponding variables, we could do like this:
(function() {
var productCategories = [
[{
"id": 1,
"name": "Product 1",
"created_at": "2017-06-06 08:31:34",
"updated_at": "2017-06-06 09:16:18"
},
{
"id": 2,
"name": "Product 2",
"created_at": "2017-06-06 09:16:12",
"updated_at": "2017-06-06 09:16:12"
},
{
"id": 3,
"name": "Product 3",
"created_at": "2017-06-06 09:16:24",
"updated_at": "2017-06-06 09:16:24"
}
]
];
var packageCategories = [
[{
"id": 1,
"product_id": "1",
"name": "Package 1-1",
"jumlah_user": "1",
"created_at": "2017-06-06 09:34:11",
"updated_at": "2017-06-06 09:34:11"
},
{
"id": 2,
"product_id": "1",
"name": "Package 1-2",
"jumlah_user": "1",
"created_at": "2017-06-06 09:35:49",
"updated_at": "2017-06-06 10:03:43"
},
{
"id": 3,
"product_id": "2",
"name": "Package 2-1",
"jumlah_user": "1",
"created_at": "2017-06-07 03:03:35",
"updated_at": "2017-06-07 03:03:35"
},
{
"id": 4,
"product_id": "2",
"name": "Package 2-2",
"jumlah_user": "1",
"created_at": "2017-06-07 03:30:11",
"updated_at": "2017-06-07 03:30:11"
},
{
"id": 5,
"product_id": "3",
"name": "Package 3-1",
"jumlah_user": "12",
"created_at": "2017-06-07 03:31:36",
"updated_at": "2017-06-07 03:31:36"
},
]
];
var listPrice = [
[{
"id": 1,
"package_id": "1",
"harga": "700000.00",
"masa_training": "2 x 1 jam",
"masa_maintenance": "2 bulan",
"tanggal_efektif": "2018-01-01",
"created_at": "2017-06-07 03:45:20",
"updated_at": "2017-06-07 03:45:20"
},
{
"id": 2,
"package_id": "2",
"harga": "500000.00",
"masa_training": "500",
"masa_maintenance": "100",
"tanggal_efektif": "2019-01-01",
"created_at": "2017-06-07 03:48:23",
"updated_at": "2017-06-07 03:48:23"
},
{
"id": 3,
"package_id": "3",
"harga": "50000.00",
"masa_training": "10",
"masa_maintenance": "20",
"tanggal_efektif": "2017-11-30",
"created_at": "2017-06-08 23:11:49",
"updated_at": "2017-06-08 23:11:49"
}
]
];
function buildProductCategoryMenu(productCategories) {
var ul = "",
i, obj, len = productCategories.length;
ul = "<ul class=\"list-group\">";
for (i = 0; i < len; i++) {
obj = productCategories[i];
ul += "<li class=\"btn btn-lg btn-default list-group-item btn-menu\">";
ul += "<p class=\"productid\" hidden>";
ul += obj.id;
ul += "</p>";
ul += "<p class=\"productname\">";
ul += obj.name;
ul += "</p>";
ul += "</li>";
}
ul += "</ul>";
return ul;
}
function setEventsProductCategoryMenu() {
var elems = document.getElementsByClassName("productname"),
i, len = elems.length,
ele;
for (i = 0; i < len; i++) {
ele = elems[i];
ele.onclick = function() {
showPackageName(this.previousSibling.innerHTML, packageCategories[0]);
};
}
}
function showPackageName(id, packageCategories) {
var packageCategory = packageCategories.find(function(x) {
return x.product_id === id;
});
if (packageCategory !== undefined) {
document.getElementById("packageName").innerHTML = "Package Name: " + packageCategory.name;
document.getElementById("price").innerHTML = "Price: " + showPriceBasedPackageCategory(packageCategory.id, listPrice[0]);
}
}
function showPriceBasedPackageCategory(id, listPrice) {
var obj;
obj = listPrice.find(function(x) {
return x.package_id === id.toString();
});
return (obj === undefined) ? "" : obj.harga;
}
document.getElementById("menu").innerHTML = buildProductCategoryMenu(productCategories[0]);
setEventsProductCategoryMenu();
})();
#menu {
border: solid 1px #ccc;
}
#content {
border: solid 1px #555;
}
<div id="menu"></div>
<div id="content">
<p id="packageName"></p>
<p id="price"></p>
</div>
With AJAX (Native JavaScript XMLHttpRequest() object):
By using a simple json file which contains all the data getting from the server.
JSON File: https://gist.githubusercontent.com/dannyjhonston/786a8e7c3f4ff1a0569013a1d4d1b8ad/raw/eb62b89d43e310997f9507be2d25f7fa375ddb6c/productCategoryPackageCategoryListPrice.json
(function() {
var newXHR = null;
// XMLHttpRequest helper function.
function sendXHR(type, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response);
}
};
}
function buildProductCategoryMenu(productCategories) {
var ul = "",
i, obj, len = productCategories.length;
ul = "<ul class=\"list-group\">";
for (i = 0; i < len; i++) {
obj = productCategories[i];
ul += "<li class=\"btn btn-lg btn-default list-group-item btn-menu\">";
ul += "<p class=\"productid\" hidden>";
ul += obj.id;
ul += "</p>";
ul += "<p class=\"productname\">";
ul += obj.name;
ul += "</p>";
ul += "</li>";
}
ul += "</ul>";
return ul;
}
function setEventsProductCategoryMenu(packageCategories, listPrice) {
var elems = document.getElementsByClassName("productname"),
i, len = elems.length,
ele;
for (i = 0; i < len; i++) {
ele = elems[i];
ele.onclick = function() {
showPackageName(this.previousSibling.innerHTML, packageCategories, listPrice);
};
}
}
function showPackageName(id, packageCategories, listPrice) {
var packageCategory = packageCategories.find(function(x) {
return x.product_id === id;
});
if (packageCategory !== undefined) {
document.getElementById("packageName").innerHTML = "Package Name: " + packageCategory.name;
document.getElementById("price").innerHTML = "Price: " + showPriceBasedPackageCategory(packageCategory.id, listPrice);
}
}
function showPriceBasedPackageCategory(id, listPrice) {
var obj;
obj = listPrice.find(function(x) {
return x.package_id === id.toString();
});
return (obj === undefined) ? "" : obj.harga;
}
sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/786a8e7c3f4ff1a0569013a1d4d1b8ad/raw/eb62b89d43e310997f9507be2d25f7fa375ddb6c/productCategoryPackageCategoryListPrice.json", null, function(response) {
if (response !== null && response.length > 0) {
var jsonResponse = JSON.parse(response);
document.getElementById("menu").innerHTML = buildProductCategoryMenu(jsonResponse.data.productCategories[0]);
setEventsProductCategoryMenu(jsonResponse.data.packageCategories[0], jsonResponse.data.listPrice[0]);
}
});
})();
#menu {
border: solid 1px #ccc;
}
#content {
border: solid 1px #555;
}
<div id="menu"></div>
<div id="content">
<p id="packageName"></p>
<p id="price"></p>
</div>
By using three json files which contains its corresponding data getting from the server.
JSON Files:
Product Categories: https://gist.githubusercontent.com/dannyjhonston/3e2689ac7197d69a9624b32d5600e150/raw/18e36651acb9b9883732081a18c7deae7388eb0f/productCategories.json.
Package Categories: https://gist.githubusercontent.com/dannyjhonston/5d0caaffd3e22506fe1311eb4e31b7cc/raw/09a305b83cb725907d8ee9c24d487bdd85591b14/packageCategories.json.
List Price: https://gist.githubusercontent.com/dannyjhonston/cd73c2caf8d53ff1f453eafc14046357/raw/c943af91e7dd3e5e14e5763d8a2a14f649ddd810/listPrice.json.
(function() {
var newXHR = null;
// XMLHttpRequest helper function.
function sendXHR(type, url, data, callback) {
newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
newXHR.open(type, url, true);
newXHR.send(data);
newXHR.onreadystatechange = function() {
if (this.status === 200 && this.readyState === 4) {
callback(this.response);
}
};
}
function buildProductCategoryMenu(productCategories) {
var ul = "",
i, obj, len = productCategories.length;
ul = "<ul class=\"list-group\">";
for (i = 0; i < len; i++) {
obj = productCategories[i];
ul += "<li class=\"btn btn-lg btn-default list-group-item btn-menu\">";
ul += "<p class=\"productid\" hidden>";
ul += obj.id;
ul += "</p>";
ul += "<p class=\"productname\">";
ul += obj.name;
ul += "</p>";
ul += "</li>";
}
ul += "</ul>";
return ul;
}
function setEventsProductCategoryMenu(packageCategories, listPrice) {
var elems = document.getElementsByClassName("productname"),
i, len = elems.length,
ele;
for (i = 0; i < len; i++) {
ele = elems[i];
ele.onclick = function() {
showPackageName(this.previousSibling.innerHTML, packageCategories, listPrice);
};
}
}
function showPackageName(id, packageCategories, listPrice) {
var packageCategory = packageCategories.find(function(x) {
return x.product_id === id;
});
if (packageCategory !== undefined) {
document.getElementById("packageName").innerHTML = "Package Name: " + packageCategory.name;
document.getElementById("price").innerHTML = "Price: " + showPriceBasedPackageCategory(packageCategory.id, listPrice);
}
}
function showPriceBasedPackageCategory(id, listPrice) {
var obj;
obj = listPrice.find(function(x) {
return x.package_id === id.toString();
});
return (obj === undefined) ? "" : obj.harga;
}
sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/3e2689ac7197d69a9624b32d5600e150/raw/18e36651acb9b9883732081a18c7deae7388eb0f/productCategories.json", null, function(response) {
if (response !== null && response.length > 0) {
var jsonResponse = JSON.parse(response);
document.getElementById("menu").innerHTML = buildProductCategoryMenu(jsonResponse.productCategories[0]);
sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/5d0caaffd3e22506fe1311eb4e31b7cc/raw/09a305b83cb725907d8ee9c24d487bdd85591b14/packageCategories.json", null, function(response) {
if (response !== null && response.length > 0) {
jsonResponse = JSON.parse(response);
var packageCategories = jsonResponse.packageCategories;
sendXHR("GET", "https://gist.githubusercontent.com/dannyjhonston/cd73c2caf8d53ff1f453eafc14046357/raw/c943af91e7dd3e5e14e5763d8a2a14f649ddd810/listPrice.json", null, function(response) {
if (response !== null && response.length > 0) {
jsonResponse = JSON.parse(response);
var listPrice = jsonResponse.listPrice;
setEventsProductCategoryMenu(packageCategories[0], listPrice[0]);
}
});
}
});
}
});
})();
#menu {
border: solid 1px #ccc;
}
#content {
border: solid 1px #555;
}
<div id="menu"></div>
<div id="content">
<p id="packageName"></p>
<p id="price"></p>
</div>
Related
I am using django templates and having JSON data to render on it.
But problem is the first row is empty when more then 1 object created using iteration. and last object have data (td's ) of one extra row.
The code is here-
Passed JSON objectis like this one:
{"Academics": {"IB": {"IB_1st": {
"id": 12, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "IB", "tuition_class__name": "1st", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"12": "German"}
},
"IB_Pre-Primary": {
"id": 2339, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "IB", "tuition_class__name": "Pre-Primary",
"stream__name": null, "subject__name": "German", "streams": [null], "subjects": {"2339": "German"}
}
},
"CBSE": {"CBSE_2nd": {
"id": 13, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "CBSE", "tuition_class__name": "2nd", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"13": "German"}},
"CBSE_3rd": {
"id": 15, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "CBSE", "tuition_class__name": "3rd", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"15": "German"}
}
}
}}
Element creation using JQUERY in django templates:
function myFun(group_list_record) {
var group_dict_record = group_list_record[0];
var table = $('<table>');
var content = '<thead><tr><th>CATEGORY</th> <th>BOARD</th> <th>TUITION CLASS </th> <th>STREAM</th> <th>SUBJECT</th></tr></thead>';
table_body = $('<tbody>');
$(table).append(content);
for (var category_key in group_dict_record) {
var category = category_key;
var category_dict = group_dict_record[category_key];
if (group_dict_record.hasOwnProperty(category_key)) {
console.log(category_key + " -> " + group_dict_record[category_key]);
for (var board_key in category_dict) {
console.log(" "+board_key + " -> " + category_dict[board_key]);
var board = board_key;
var board_dict = category_dict[board_key];
for (var board_tuition_key in board_dict) {
console.log(" "+board_tuition_key + " -> " + board_dict[board_tuition_key]);
var table_row = $('<tr>').addClass(board_tuition_key); // .attr('id', board_tuition_key);
var board_tuition = board_tuition_key;
var board_tuition_dict = board_dict[board_tuition_key];
for (var records_key in board_tuition_dict) {
console.log(records_key);
if (records_key == 'category__type')
{
var category_column = $('<td>');
category_column.text(board_tuition_dict.category__type);
}
if (records_key == 'board__name')
{
var board_column = $('<td>');
board_column.text(board_tuition_dict.board__name);
}
if (records_key == 'tuition_class__name')
{
var tuition_class_column = $('<td>');
tuition_class_column.text(board_tuition_dict.tuition_class__name);
}
if (records_key == 'streams')
{
var stream_column = $('<td>');
stream_column.text(board_tuition_dict.streams);
}
if (records_key == 'subjects')
{
var subjects_column = $('<td>');
for (sub in board_tuition_dict.subjects)
{
var subject_name = board_tuition_dict.subjects[sub];
var delete_tag = $('<div>').addClass('delete-group-sepc').text(subject_name);
console.log(" Subjects:"+sub + " -> " + board_tuition_dict.subjects[sub]);
subjects_column.append(delete_tag);
delete_tag.attr('data-id', sub);
}
}
table_row.append(category_column);
table_row.append(board_column);
table_row.append(tuition_class_column);
table_row.append(stream_column);
table_row.append(subjects_column);
}
table_body.append(table_row).attr('id', board_tuition_key);
}
}
}
}
table.append(table_body);
$('#ajax_response').append(table);
// $('#ajax_response').children().replaceWith(table);
}
providing image of the output screen:
check it out here
note the empty in the image.
There is a problem in this block: you append fields (category_column, board_column etc) multiple times.
table_row.append(category_column);
table_row.append(board_column);
table_row.append(tuition_class_column);
table_row.append(stream_column);
table_row.append(subjects_column);
I prepared a snippet that is working:
var group_list_record = [{
"Academics": {
"IB": {
"IB_1st": {
"id": 12, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "IB", "tuition_class__name": "1st", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"12": "German"}
},
"IB_Pre-Primary": {
"id": 2339, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "IB", "tuition_class__name": "Pre-Primary",
"stream__name": null, "subject__name": "German", "streams": [null], "subjects": {"2339": "German"}
}
},
"CBSE": {
"CBSE_2nd": {
"id": 13, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "CBSE", "tuition_class__name": "2nd", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"13": "German"}
},
"CBSE_3rd": {
"id": 15, "group": 2, "group__group_group": "Academics-CBSE/IB-upto5th", "group__name": "German",
"category__type": "Academics", "board__name": "CBSE", "tuition_class__name": "3rd", "stream__name": null,
"subject__name": "German", "streams": [null], "subjects": {"15": "German"}
},
}
}
}];
function myFun(group_list_record) {
var group_dict_record = group_list_record[0];
var table = $('<table>');
var content = '<thead><tr><th>CATEGORY</th> <th>BOARD</th> <th>TUITION CLASS </th> <th>STREAM</th> <th>SUBJECT</th></tr></thead>';
table_body = $('<tbody>');
$(table).append(content);
for (var category_key in group_dict_record) {
var category = category_key;
var category_dict = group_dict_record[category_key];
if (group_dict_record.hasOwnProperty(category_key)) {
// console.log(category_key + " -> " + group_dict_record[category_key]);
for (var board_key in category_dict) {
// console.log(" "+board_key + " -> " + category_dict[board_key]);
var board = board_key;
var board_dict = category_dict[board_key];
for (var board_tuition_key in board_dict) {
// console.log(" "+board_tuition_key + " -> " + board_dict[board_tuition_key]);
var table_row = $('<tr>').addClass(board_tuition_key); // .attr('id', board_tuition_key);
var board_tuition = board_tuition_key;
var board_tuition_dict = board_dict[board_tuition_key];
for (var records_key in board_tuition_dict) {
// console.log("records_key: " + records_key);
if (records_key == 'category__type')
{
var category_column = $('<td>');
category_column.text(board_tuition_dict.category__type);
}
if (records_key == 'board__name')
{
var board_column = $('<td>');
board_column.text(board_tuition_dict.board__name);
}
if (records_key == 'tuition_class__name')
{
var tuition_class_column = $('<td>');
tuition_class_column.text(board_tuition_dict.tuition_class__name);
}
if (records_key == 'streams')
{
var stream_column = $('<td>');
stream_column.text(board_tuition_dict.streams);
}
if (records_key == 'subjects')
{
var subjects_column = $('<td>');
for (sub in board_tuition_dict.subjects)
{
var subject_name = board_tuition_dict.subjects[sub];
var delete_tag = $('<div>').addClass('delete-group-sepc').text(subject_name);
// console.log(" Subjects:"+sub + " -> " + board_tuition_dict.subjects[sub]);
subjects_column.append(delete_tag);
delete_tag.attr('data-id', sub);
}
}
/* this is a wrong place
table_row.append(category_column);
table_row.append(board_column);
table_row.append(tuition_class_column);
table_row.append(stream_column);
table_row.append(subjects_column);
*/
}
/* this is a correct place */
/* preparing all fields in a loop and than append it once */
table_row.append(category_column);
table_row.append(board_column);
table_row.append(tuition_class_column);
table_row.append(stream_column);
table_row.append(subjects_column);
table_body.append(table_row).attr('id', board_tuition_key);
}
}
}
}
table.append(table_body);
$('#ajax_response').append(table);
// $('#ajax_response').children().replaceWith(table);
}
myFun(group_list_record);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="ajax_response"></div>
Consider breaking up the functions a bit more. For example:
$(function() {
function makeTable(tObj, props) {
if (tObj == undefined) {
tObj = false;
}
var t;
if (props == undefined) {
t = $("<table>");
} else {
t = $("<table>", props);
}
$("<thead>").appendTo(t);
$("<tbody>").appendTo(t);
if (tObj) {
t.appendTo(tObj);
}
console.log("Created Table");
return t;
}
function populateHead(tbl, keyArr) {
var thd;
if ($("thead", tbl).length) {
thd = $("thead", tbl);
} else {
thd = $("<thead>").appendTo(tbl);
}
var row = $("<tr>").appendTo(thd);
var c = 0;
$.each(keyArr, function(i, k) {
$("<th>").html(k).appendTo(row);
c++;
});
console.log("Created " + c + " Headers");
return c;
}
function populateBody(tbl, dataArr) {
var tbd, row, c = 0;
if ($("tbody", tbl).length) {
tbd = $("tbody", tbl);
} else {
tbd = $("<tbody>").appendTo(tbl);
}
$.each(dataArr, function(i, r) {
row = $("<tr>").appendTo(tbd);
c++;
$.each(r, function(j, c) {
$("<td>").html(c).appendTo(row);
});
});
console.log("Created " + c + " Rows");
return c;
}
function makeTableData(o) {
var d = [];
var cats = Object.keys(o);
var r = [];
$.each(o[cats[0]], function(k, v) {
r.push(cats[0]);
r.push(k);
$.each(v, function(j, x) {
r.push(x['tuition_class__name']);
r.push(x['stream__name']);
r.push(x['subject__name']);
});
d.push(r);
});
console.log("Data:", d);
return d;
}
As you can see, now you can focus more on just creating an Array of table data.
[ // Row container
["cell 1", "cell 2", "cell 3"],
["cell 1", "cell 2", "cell 3"],
["cell 1", "cell 2", "cell 3"]
];
You would configure this algorithm in the makeTableData() function. Feed in your object (from AJAX I assume) and then feed the resulting matrix into populateBody() function.
I have bellow mentioned of dynamic js object form which I try to convert it to Schema Data and add into head tag of the web page for SEO purpose.
Not sure how it can be possible as I am new staff on this.
My JS Function:
function populateJsonLDScript(data) {
if (typeof (data) != "undefined" && data != null) {
var finalSchemaObj = {};
var tempSchemaItems = [];
for (var i = 0; i < data.length; i++) {
var tempSchemaData = {};
tempSchemaData["#type"] = "ListItem";
tempSchemaData["position"] = data[i].DisplayOrder;
tempSchemaData["item"] = {
"#id": data[i].CanonicalURL,
"name": data[i].Name
};
tempSchemaItems.push(tempSchemaData);
}
for (var i = 0; i < tempSchemaItems.length; ++i) {
finalSchemaObj[i] = tempSchemaItems[i];
}
var scriptSchema = document.createElement('script');
scriptSchema.type = 'application/ld+json';
scriptSchema.text = JSON.stringify({
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": [finalSchemaObj]
});
if ($('head script[type="application/ld+json"]').length > 0) {
$('head script[type="application/ld+json"]').remove();
$("head").append(scriptSchema);
} else {
$("head").append(scriptSchema);
}
}
}
OUTPUT
{
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": [{
"0": {
"#type": "ListItem",
"position": 0,
"item": {
"#id": "http://example.com",
"name": "Home"
}
},
"1": {
"#type": "ListItem",
"position": 1,
"item": {
"#id": "http://example.com/jewelry",
"name": "Jewelry"
}
},
"2": {
"#type": "ListItem",
"position": 2,
"item": {
"#id": "http://example.com/jewelry/necklaces-pendants",
"name": "Necklaces & Pendants"
}
}
}]
}
But Still Google said its invalid format. So, I want to format the above to -
{"#context":"http://schema.org","#type":"BreadcrumbList","itemListElement":[
{
"#type":"ListItem",
"position":0,
"item": {
"#id":"http://example.com",
"name":"Home"
}
},
{
"#type":"ListItem",
"position":1,
"item":{
"#id":"http://example.com/jewelry",
"name":"Jewelry"
}
},
{
"#type":"ListItem",
"position":2,
"item":{
"#id":"http://example.com/jewelry/necklaces-pendants",
"name":"Necklaces & Pendants"
}
}
]
}
Anyone please help how to do this?
Don't use object, use array and push into it. Something like this:
function populateJsonLDScript(data) {
if (typeof(data) != "undefined" && data != null) {
var finalSchemaObj = []; // <----- use array here
var tempSchemaItems = [];
for (var i = 0; i < data.length; i++) {
var tempSchemaData = {};
tempSchemaData["#type"] = "ListItem";
tempSchemaData["position"] = data[i].DisplayOrder;
tempSchemaData["item"] = {
"#id": data[i].CanonicalURL,
"name": data[i].Name
};
tempSchemaItems.push(tempSchemaData);
}
for (var i = 0; i < tempSchemaItems.length; ++i) {
finalSchemaObj.push(tempSchemaItems[i]); // <--- push here
}
var scriptSchema = document.createElement('script');
scriptSchema.type = 'application/ld+json';
scriptSchema.text = JSON.stringify({
"#context": "http://schema.org",
"#type": "BreadcrumbList",
"itemListElement": finalSchemaObj // <----- and use finalSchemaObj here
});
if ($('head script[type="application/ld+json"]').length > 0) {
$('head script[type="application/ld+json"]').remove();
$("head").append(scriptSchema);
} else {
$("head").append(scriptSchema);
}
}
}
I want to stack divs one after another, by class, so if div has class of "icon1" then the following div will be "icon2". I want to to id within the each loop.. to prevent multiple Dom manipulations
var arr = [{
"id": 1,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}, {
"id": 2,
"name": "foo"
}, {
"id": 1,
"name": "foo"
}];
var type = '';
var template ='';
$.each(arr, function() {
if (this['id'] == 1) {
type = 'icon1';
} else {
type = 'icon2';
}
template += '<div class="icon '+type+'">'+
'<p>ID: '+type+' Name: '+this['name']+'<p></div>';
});
$('#foo').html(template);
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
</div>
The result i'm looking for will be :
icon1
icon2
icon1
icon2
icon1
icon2
etc...
This is a solution:
var array = [
{
"id": 1,
"name": "foo"
},
{
"id": 1,
"name": "foo"
},
{
"id": 2,
"name": "foo"
},
{
"id": 1,
"name": "foo"
}
];
var lsts = [ [], [] ];
$.each( array, function() {
lsts[ this.id - 1 ].push( this );
} );
var lst1 = lsts[ 0 ],
lst2 = lsts[ 1 ];
for ( var i = 0, l = lst1.length, l2 = lst2.length; i < l || i < l2; i++ ) {
if ( i < l )
appendElement( lst1[ i ] );
if ( i < l2 )
appendElement( lst2[ i ] );
}
function appendElement( obj ) {
$( '#bar' ).append( '<div class="icon' + obj.id + '">' + obj.name + '</div>' );
}
.icon1 {
color: red;
}
.icon2 {
color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bar"><div>
Beware of another ID numbers.
You can use css nth-child property to get this styles
div:nth-child(odd) {
color: red;
}
div:nth-child(even) {
color: pink;
}
I have a object containing list of item data. I need to group items based on stockTypeCd and display Product 1, Product 2 in one row and Product 3 in another row as it has a different stockTypeCd. Here is the sample JSON that am getting in Angular Controller from Java Rest services. I cannot change the way my json response from java. Here is the sample json
{
"availableItems":[
{
"stockCategoryId":200005,
"stock":{
"stockId":100005,
"stockTypeCd":2,
"name":"Product 1"
},
},
{
"stockCategoryId":200006,
"stock":{
"stockId":100006,
"stockTypeCd":2,
"name":"Product 2"
},
},
{
"stockCategoryId":220005,
"stock":{
"stockId":110005,
"stockTypeCd":1,
"name":"Product 3"
},
}
]
}
When user clicks submit, i get a json like this one and i have to group elements and display in the UI table.
You could use Array.reduce() to use stock.stockTypeCd as key.
This is a sample:
function groupItems(data) {
var grouped = data.availableItems.reduce(function(result, current) {
result[current.stock.stockTypeCd] = result[current.stock.stockTypeCd] || [];
result[current.stock.stockTypeCd].push(current);
return result;
}, {});
return grouped;
}
So, you can convert this:
{
"availableItems":[
{
"stockCategoryId":200005,
"stock":{
"stockId":100005,
"stockTypeCd":2,
"name":"Product 1"
},
},
{
"stockCategoryId":200006,
"stock":{
"stockId":100006,
"stockTypeCd":2,
"name":"Product 2"
},
},
{
"stockCategoryId":220005,
"stock":{
"stockId":110005,
"stockTypeCd":1,
"name":"Product 3"
},
}
]
}
To this:
{
"1": [
{
"stockCategoryId": 220005,
"stock": {
"stockId": 110005,
"stockTypeCd": 1,
"name": "Product 3"
}
}
],
"2": [
{
"stockCategoryId": 200005,
"stock": {
"stockId": 100005,
"stockTypeCd": 2,
"name": "Product 1"
}
},
{
"stockCategoryId": 200006,
"stock": {
"stockId": 100006,
"stockTypeCd": 2,
"name": "Product 2"
}
}
]
}
With the new array you can print the results in a html table by using this function:
function printResults(data) {
var i, len, html = "<table border=\"1\">";
html += "<thead><tr><th>stockTypeCd</th><th>Stock</th></thead><tbody>";
for (item in data) {
html += "<tr><td>";
html += item;
html += "</td><td><table>";
len = data[item].length;
if (len > 0) {
for (i = 0; i < len; i++) {
html += "<tr><td><span>stockId: </span>";
html += data[item][i].stock.stockId;
html += "</td></tr><td><span>name: </span>";
html += data[item][i].stock.name;
html += "</td></tr>";
}
html += "</table>";
}
html += "</td></tr>";
}
html += "</tbody></table>";
return html;
}
So you can get this:
Usage:
document.getElementById("result").innerHTML = printResults(groupItems(data));
Something like this:
(function() {
var data = {
"availableItems": [{
"stockCategoryId": 200005,
"stock": {
"stockId": 100005,
"stockTypeCd": 2,
"name": "Product 1"
},
},
{
"stockCategoryId": 200006,
"stock": {
"stockId": 100006,
"stockTypeCd": 2,
"name": "Product 2"
},
},
{
"stockCategoryId": 220005,
"stock": {
"stockId": 110005,
"stockTypeCd": 1,
"name": "Product 3"
},
}
]
};
function groupItems(data) {
var grouped = data.availableItems.reduce(function(result, current) {
result[current.stock.stockTypeCd] = result[current.stock.stockTypeCd] || [];
result[current.stock.stockTypeCd].push(current);
return result;
}, {});
return grouped;
}
function printResults(data) {
var i, len, html = "<table border=\"1\">";
html += "<thead><tr><th>stockTypeCd</th><th>Stock</th></thead><tbody>";
for (item in data) {
html += "<tr><td>";
html += item;
html += "</td><td><table>";
len = data[item].length;
if (len > 0) {
for (i = 0; i < len; i++) {
html += "<tr><td><span>stockId: </span>";
html += data[item][i].stock.stockId;
html += "</td></tr><td><span>name: </span>";
html += data[item][i].stock.name;
html += "</td></tr>";
}
html += "</table>";
}
html += "</td></tr>";
}
html += "</tbody></table>";
return html;
}
document.getElementById("result").innerHTML = printResults(groupItems(data));
})();
#result table {
border-collapse: collapse;
}
#result table thead {
background-image: linear-gradient(#daebf7, #9fbfe6);
}
#result table th,
#result table td {
border: solid 1px #CCCCCC;
padding: 5px;
}
#result table td span {
font-weight: bold;
}
<div id="result"></div>
This creates a map of availableItems using stockTypeCd as the key. You can iterate over it and apply any sort of business logic that you desire
var data = {
"availableItems": [{
"stockCategoryId": 200005,
"stock": {
"stockId": 100005,
"stockTypeCd": 2,
"name": "Product 1"
},
},
{
"stockCategoryId": 200006,
"stock": {
"stockId": 100006,
"stockTypeCd": 2,
"name": "Product 2"
},
},
{
"stockCategoryId": 220005,
"stock": {
"stockId": 110005,
"stockTypeCd": 1,
"name": "Product 3"
},
}
]
}
// Map of stockTypeCd to availableItems
var groupedData = {};
data.availableItems.forEach(function(item) {
// If map doesn't contain the stockTypeCd, create a new entry
if (!groupedData.hasOwnProperty(item.stock.stockTypeCd)) {
groupedData[item.stock.stockTypeCd] = []
}
groupedData[item.stock.stockTypeCd].push(item);
});
console.log(groupedData);
My JSON looks like this:
{
"features": [
{
"id": "belly",
"scenarios": [
{
"id": "belly;a-few-cukes",
"tags": [
{
"name": "#tag1"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growls"
}
]
},
{
"id": "belly;a-few-cukes-with-new-test",
"tags": [
{
"name": "#tag2"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growl"
}
]
}
]
},
{
"id": "newbelly",
"scenarios": [
{
"id": "newbelly;a-few-cukes-with-new-feature",
"tags": [
{
"name": "#tag1"
}
],
"steps": [
{
"name": "I have 42 cukes in my belly"
},
{
"name": "I wait 1 hour"
},
{
"name": "my belly should growls"
}
]
}
]
}
]
}
I would like to retrieve all the unique tag names: i.e., #tag1, #tag2. If you notice, the #tag1 is repeated twice.
My template:
{{#getTags features}}
{{#scenarios}}
{{#tags}}
<p>{{name}}</p>
{{/tags}}
{{/scenarios}}
{{/getTags}}
Custom Helper that I created so far:
Handlebars.registerHelper('getTags', function(context, block) {
var ret = "";
for (var i = 0; i < context.length; i++) {
ret += block.fn(context[i]);
};
return ret;
});
The above custom helper returns all the tags, but I want unique ones.
Something along these lines may work:
Handlebars.registerHelper('getTags', function(context, block) {
var ret = "";
var got = [];
function contains(obj, a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
for (var i = 0; i < context.length; i++) {
if (!this.contains(context[i],got)) {
got.addObject(context[i]);
ret += block.fn(context[i]);
}
}
return ret;
});
Code used for testing, all javascript:
var ret = "";
var got = [];
var data = ["tag1", "tag1", "tag2", "tag3"]
function contains(obj, a) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
for (var i = 0; i < data.length; i++) {
if (!contains(data[i],got)) {
got.push(data[i]);
ret += data[i];
}
}
console.log( ret);