how to loop through a four level json array using jquery - javascript

Four level JSON data
{
"Asia": [
{
"continentCode": "GT113",
"regionList": [
{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [
{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [
{
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}
]
},
{
"countryName": "Hong Kong",
"countryCode": "GC303"
}
]
},
{
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [
{
"countryName": "India",
"countryCode": "GC304"
},
{
"countryName": "Pakistan",
"countryCode": "GC309"
}
]
}
]
}
]
}
I have fetched the data upto 3 level and dispalyed upto 2 level. But cant able to fetch the 4th level data and display the 3rd and 4th level of data.
$.each(json, function (i1, object) {
alert(i1);
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
alert(region.regionName);
$.each(region.Countrylist, function (i4, country) {
alert(country.countryName);
if (!$("ul." + i1).is("*")) {
$("<ul />", {
"class": i1,
"html": "<li>" + region.regionName + "</li>"
}).appendTo("div").before('<b class=' + i1 + ' ><a name="' + i1 + '" >' + i1 + '</a></b>');
}else{
$("b." + i1).each(function() {
var text = this.textContent || this.innerText;
if (text === i1) {
$(this).next("ul").append("<li>" + region.regionName + "</li>");
}
});
}
/* $.each(country.subCountryList, function (i5, subCountry) {
alert(subCountry.subCountryName);
}); */
});
});
});
});
})
<div>
<ul></ul>
</div>
How to fetch the others to display as below
Asia
Eastern Asia
China -
Southern China
Hongkong
Southern Asia

Try this, using some code of #dimitar:
var json = {
"Asia": [{
"continentCode": "GT113",
"regionList": [{
"regionName": "Eastern Asia",
"regionCode": "GR128",
"Countrylist": [{
"countryName": "China",
"countryCode": "GC302",
"subCountryList": [{
"subCountryName": "Northern China",
"subCountryCode": "GR207"
}, {
"subCountryName": "Southern China",
"subCountryCode": "GR206"
}]
}, {
"countryName": "Hong Kong",
"countryCode": "GC303"
}]
}, {
"regionName": "Southern Asia",
"regionCode": "GR134",
"Countrylist": [{
"countryName": "India",
"countryCode": "GC304"
}, {
"countryName": "Pakistan",
"countryCode": "GC309"
}]
}]
}]
};
var html = '';
$.each(json, function(i1, object) {
html += '<li><b>' + i1 + '</b>';
$.each(object, function(i2, continent) {
html += '<ul>';
$.each(continent.regionList, function(i3, region) {
html += '<li><b>' + region.regionName + '</b>';
$.each(region.Countrylist, function(i4, country) {
html += '<ul><li>' + country.countryName;
if (country.subCountryList) {
html += "<ul>";
$.each(country.subCountryList, function(i5, subCountry) {
html += '<li>' + subCountry.subCountryName + '</li>';
});
html += "</ul>";
};
html += '</li></ul>';
});
html += '</li>';
});
html += '</ul>';
});
html += '</li>';
});
$('#list').html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id='list'></ul>

You will want to loop through all of them and print out something on each level.
Here is an example, tweak it to your liking and style it.
$.each(json, function (i1, object) {
console.log(i1);
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
console.log(region.regionName);
$.each(region.Countrylist, function (i4, country) {
console.log(country.countryName);
if(country.subCountryList){
$.each(country.subCountryList, function (i5, subCountry) {
console.log(subCountry.subCountryName);
});
};
});
});
});
});
Here json is your JSON you provided and we print out the list you wanted in the console.
Edited original code:
$.each(json, function (i1, object) {
$("ul").append("<li><strong>"+i1+"</li></strong>");
$.each(object, function (i2, continent) {
$.each(continent.regionList, function (i3, region) {
$("ul").append("<li><p><strong>"+region.regionName+"</li></p></strong>");
$.each(region.Countrylist, function (i4, country) {
$("ul").append("<li><p>"+country.countryName+"</li></p>");
if(country.subCountryList){
$.each(country.subCountryList, function (i5, subCountry) {
$("ul").append("<li><p>"+subCountry.subCountryName+"</li></p>");
});
};
});
});
});
});
Leave me a comment if there are still issues, I am not getting any.

Related

How to make a dropdown of the data receive from ajax response as array of objects

I want to make a dropdown in my table which is populated with the dynamic data coming from ajax response and append to the table.
My postman collection looks like this.
{
"createdDate": "2022-04-06T11:42:37.360Z",
"enabled": true,
"_id": "62502b868daa3b1cdbdc98e8",
"CNIC": "40740c7d9f3a11d93e76af7f2f60887a",
"employeeID": "LE44337",
"fName": "HUSNAIN",
"company": "6249fdf91399dc7a14173dcd",
"fatherName": "husnain",
"motherName": "momutaz",
"spouse": "no spouse",
"children": [{
"_id": "62502b868daa3b1cdbdc98e9",
"name": "hunsian",
"age": 23232
}, {
"_id": "62502b868daa3b1cdbdc98ea",
"name": "hunsian",
"age": 12121
}, {
"_id": "62502b868daa3b1cdbdc98eb",
"name": "momin",
"age": 2323
}
}
And below is my ajax response code in which I am appending the data into table.
success : function(response){
var trHTML = '';
$.each(response.doc, function (i, item) {
trHTML += '<tr><td>' + item.fName + '</td><td>' + item.CNIC + '</td><td>' + item.spouse + '</td><td>'+ item.fatherName + '</td><td>' + item.motherName +'</td><td>'+ item.employeeID +'</td><td>' + item.children.map(({name, age}) => `Name: ${name} Age: ${age}`).join(' || ') +'</td></tr>';
});
$('#records_table').append(trHTML);
}
The itme.children name , age I want to make a dropdown of it into table so it looks good.
If you mean a dropdown like a select menú, this should do the job
trHTML += `... <td>
<select>
<option selected disabled>Click me</option>` +
item.children.map(({name + age}) => `<option>Name: ${name}, Age: ${age}</option>`).join('') +
`</select></td>`;

Using Ajax to loop through nested Array to retrieve data

Good Morning, using ajax call I am trying to return the values of a nested json array, I was successful to pull the data except for the nested array "booking_status". When I try loop through the 'booking_status', I git the value [object Object],[object Object],[object Object] . If I try to specify a value for example item.booking_status.status I get this undefined.
This is my nested array
[
{
"id": 1,
"item_name": "Misrry",
"author": "Stephen King",
"booking_status": [
{
"check_in": "2021-09-22T08:27:00+04:00",
"check_out": "2021-09-23T08:27:00+04:00",
"status": "Currently Booked"
},
{
"check_in": "2021-09-25T08:37:00+04:00",
"check_out": "2021-09-26T08:37:00+04:00",
"status": "Currently Free"
},
{
"check_in": "2021-09-27T08:37:00+04:00",
"check_out": "2021-09-28T08:37:00+04:00",
"status": "Currently Free"
}
]
{
"id": 2,
"item_name": "Rose Red",
"author": "Stephen King",
"booking_status": [
{
"check_in": "2021-09-22T08:27:00+04:00",
"check_out": "2021-09-23T08:27:00+04:00",
"status": "Currently Booked"
},
{
"check_in": "2021-09-25T08:37:00+04:00",
"check_out": "2021-09-26T08:37:00+04:00",
"status": "Currently Free"
}
]
}
]
and this is my script:
<script>
$(document).ready(function () {
$.ajax({
url: 'http://localhost:8000/',
dataType: 'JSON',
success: function (data) {
for (var i = 0; i < data.length; i++) {
$(document).ready(function () {
var content = ''
data.forEach(item => {
content += "<tr><td>"
+ item.item_name + "</td><td>"
+ item.author + "</td><td>" + item.booking_status
+ "</td></td></tr>"
})
$('#table_body').html(content);
})
}
}
});
});
</script>
You have a couple of mistakes in your code.
You're iterating over data twice. (for loop and data.forEach);
Remove the for loop, it's redundant.
booking_status is an array, so you're going to have to stringify it, or iterate over it somehow.
You don't need to nest $(document).ready. The inner calls can be removed.
$(document).ready(function() {
$.ajax({
url: 'http://localhost:8000/',
dataType: 'JSON',
success: function(data) {
var content = '';
data.forEach(item => {
content += "<tr><td>" +
item.item_name + "</td><td>" +
item.author + "</td><td>" + item.booking_status.map(s => s.status).join('<br/>') +
"</td></td></tr>";
});
$('#table_body').html(content);
});
});
});

List categories and show subcategories when select category with json

I made a page like this with json. I added my test example the link at the bottom of the article. I listed the categories in this way with json. But there is something else I want. After selecting the category, I want to show the subcategories of the selected category on the screen, on the same page, maybe in the same area. How can I do this?
these are the codes I added as an example. You can see the site I prepared at the bottom of the article.
So actually when the category is selected, I want to show subcategory on the screen.
HTML
<ul id="category" class="grid">
</ul>
JAVASCRİPT
$(function() {
var people = [];
$.getJSON("category.json", function (data) {
$.each(data.cat_en, function(i, f) {
var tblRow = '<li class="grid_item">' + ''+ '<div>'+'<div>'+'</img>'+'</div>'+ '<div>'+ f.cat_name + '<span>'+ f.cat_product_count +'</span>' + '</div>'+ '</div>'+''+'</li>'
$(tblRow).appendTo("#category")
})
})
})
JSON
{
"cat_en" :
[
{
"cat_name": "Aluminum Components",
"cat_url": "#",
"cat_product_count": 29
},
{
"cat_name": "Gas Springs",
"cat_url": "#",
"cat_product_count": 75
},
{
"cat_name": "Lighting Parts",
"cat_url": "#",
"cat_product_count": 271
},
{
"cat_name": "Rear View Mirrors And Components",
"cat_url": "#",
"cat_product_count": 71
},
{
"cat_name": "Freezer And Components",
"cat_url": "#",
"cat_product_count": 22
},
{
"cat_name": "Upholstery fabrics",
"cat_url": "#",
"cat_product_count": 13
}
]
}
demo site
If we assume subcategories stored in each object,
{
"cat_name": "Aluminum Components",
"cat_url": "#",
"cat_product_count": 29,
"subcats": [
{
"cat_name": "First Subcategory",
"cat_url": "#"
},
{
"cat_name": "Second Subcategory",
"cat_url": "#"
}
]
}
You may try to implement that function to your code (I don't know JQuery so I wrote in vanilla JS);
(categoryObject) => {
if (categoryObject.subcats.length > 0) {
var result = ""
categoryObject.subcats.forEach(
(subCategoryObject) => {
var template = `<li class="subcategory">${subCategoryObject.cat_name}</li>\n`
result += template
}
return result
)
}
}
JSON
{
"cat_tr": [
{
"cat_name": "Product 1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 29,
"cat_name_alt": [
{
"cat_name": "Product 1.1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 1
},
{
"cat_name": "Product 1.2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 22
}
]
},
{
"cat_name": "Product 2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 75
},
{
"cat_name": "Product 3",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 271,
"cat_name_alt": [
{
"cat_name": "Product 3.1",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 30
},
{
"cat_name": "Product 3.2",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 40
}
]
},
{
"cat_name": "Product 4",
"cat_url": "#",
"cat_img": "img/product.png",
"cat_product_count": 71
}
]
}
JS
$(function () {
var categories = [];
$.getJSON("category.json", function (data) {
categories = data.cat_tr;
$.each(categories, function (i, f) {
var cat_index = -1;
if (typeof f.cat_name_alt !== 'undefined' && f.cat_name_alt.length > 0) {
cat_index = i;
}
var tblRow = '<li class="grid_item" data-index="' + cat_index + '">' + '' + '<div class="ic_grid">' + '<div class="cat_img">' + '<img src="' + f.cat_img + '">' + '</img>' + '</div>' + '<div class="cat_dec">' + f.cat_name + '<span>' + f.cat_product_count + '</span>' + '</div>' + '</div>' + '' + '</li>'
$(tblRow).appendTo("#cat_list")
});
});
$(document).on('click', '.grid_item', function (e) {
if ($(this).data('index') != -1) {
e.preventDefault();
$('#cat_list').html('');
var sub_categories = categories[parseInt($(this).data('index'))].cat_name_alt;
$.each(sub_categories, function (i, f) {
var cat_index = -1;
if (typeof f.cat_name_alt !== 'undefined' && f.cat_name_alt.length > 0) {
cat_index = i;
}
var tblRow = '<li class="grid_item" data-index="' + cat_index + '">' + '' + '<div class="ic_grid">' + '<div class="cat_img">' + '<img src="' + f.cat_img + '">' + '</img>' + '</div>' + '<div class="cat_dec">' + f.cat_name + '<span>' + f.cat_product_count + '</span>' + '</div>' + '</div>' + '' + '</li>'
$(tblRow).appendTo("#cat_list")
});
}
});
})

Based on select field generate a table from json file

Is it possible to auto create a table from json files based on selected values.
$(document).ready(function(){
$("#dropdown_change").change(function(){
alert("Selected value is : " + document.getElementById("dropdown_change").value);
});
With your given json i'hv made an example. Look into this.
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if (projects.length) {
var html = '';
projects.map(function(pro) {
html += '<tr>';
for (var i in pro) {
html += '<td>' + pro[i] + '</td>';
}
html += '</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
var PROJECTDETAILS = [{
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "0011",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "Bluesky",
"Employee Name": "anusha",
"Issue Id": "00123",
"Charge No": "1111",
"Hours": "10"
}, {
"Project key": "project2",
"Employee Name": "kavya",
"Issue Id": "00452",
"Charge No": "1111",
"Hours": "10"
}]
$(document).ready(function() {
$("#dropdown_change").change(function() {
var val = $(this).val();
alert("Selected value is : " + val);
var projects = PROJECTDETAILS.filter(function(pd) {
return pd['Project key'] == val;
})
if(projects.length){
var html = '';
projects.map(function(pro){
html+='<tr>';
for(var i in pro){
html+='<td>'+pro[i]+'</td>';
}
html+='</tr>';
})
$('table').find('tr').not(':eq(0)').remove();
$('table').show().append(html);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown_change">
<option value="Bluesky">Bluesky</option>
<option value="project2">project2</option>
</select>
<table style="display: none">
<tr><th>Project key</th><th>Employee Name</th><th>Issue Id</th><th>Charge No</th><th>Hours</th></tr>
</table>

How to output data as HTML from JSON object using getJSON

Hello there I will try and keep this simple and short
I have a getJSON function that runs every 5 seconds. Now when I display the data using document.write function it dosent seem to want to update. The page is stuck in a loading loop. How can I get the data to display on my page? My JSON is fine but I will show you anyways.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){ $.getJSON('names.json', function(data) {
for(i in data) {
document.write(data[i] + "<br/>");
}
});
},5000);
</script>
This is the JSON object
{
"one": "",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Don't actually use document.write. Once the page is loaded, that will erase the page. Use (jQuery's) DOM methods to manipulate the DOM.
$.getJSON('names.json', function(data){
for(var i in data){
$('#myDiv').append(data[i]);
}
});
I would recommend you use jQuery,
I used this to create a form from my json item, I hope this helps...
function jsonFormCreator(frmJSON)
{
var createdHTML = ""; var elementType, id;
console.log(JSON.stringify(frmJSON));
for(item in frmJSON)
{
formElement = frmJSON[item]; elementType = formElement.elementType; id = formElement.id;
if(elementType == "input")
{
createdHTML += "<input id='" + id +"'";
if(formElement.type == "checkbox")
{createdHTML += " type='" + formElement.type + "' checked='" + formElement.checked + "'";}
else{createdHTML += "type='" + formElement.type + "' value='" + formElement.value + "' onclick='" + formElement.onclick + "'";}
createdHTML += "/><br>"
}
else if(elementType == "textarea")
{createdHTML += "<textarea id='" + formElement.id + "' rows='" + formElement.rows + "' cols='" + formElement.cols + "' value='" + formElement.value + "'></textarea><br>";}
else if(elementType == "select")
{
var options = formElement.values;
createdHTML += "<select id='" + formElement.id+ "'>";
for(i = 0 ; i < options.length ; i++)
{createdHTML += "<option value='" + options[i][0] + "'>" + options[i][1] + "</option>";} //Adding each option
createdHTML+= "</select><br>";
}
}
console.log("Complete");console.log(createdHTML);
document.getElementById('mainContainer').innerHTML = createdHTML;//Adding to the DOM
}
And my JSON would look like this
{
"0": {
"elementType": "input",
"id": "frm1",
"type": "text",
"value": "form Liam",
"label": "Test Text Input"
},
"itemBTN": {
"elementType": "input",
"id": "frmAlert",
"type": "button",
"onclick" : "loader(homePage);",
"value": "Home Page",
"label": ""
},
"item2": {
"elementType": "textarea",
"id": "frm2",
"rows": 5,
"cols": 30,
"value": "helddddddddlo",
"label": "Test Textarea"
},
"item3": {
"elementType": "select",
"id": "frm3",
"values": [
[
"value1",
"Pick Me"
],
[
"value2",
"UserDis2"
],
[
"value3",
"UserDis3"
],
[
"value4",
"UserDis4"
],
[
"value5",
"UserDis5"
],
[
"value6",
"UserDis6"
]
],
"label": "Test Select"
},
"item4": {
"elementType": "input",
"id": "frm4",
"label": "Checkbox",
"type": "checkbox",
"checked": true
}
}
This code adds the form in to my div tag with the id mainContainer
I know its alot of code, but i hope it helps !
You want to render dom which will contain the data, then when you get the data update the dom.
As an exceedingly simple example, on your page have a container
<div id="one"></div>
and then in your ajax success handler
$("#one").text(json.one);
This uses jquery to grab the dom element with id "one", and update its text.

Categories