First, your JSON is wrongly formatted and it wouldn’t even parse. Assuming the JSON object is like this:
"Categories": {
"cat1": [
{
"id": 1,
"Category_name": "cat1",
"Name": "iphone6",
"Details": "packed",
}
],
"cat2": [
{
"id": 2,
"Category_name": "cat2",
"Name": "GalaxyS10",
"Details": "stock"
}
],
"cat1": [
{
"id": 3,
"Category_name": "cat1",
"Name": "iphone5s",
"Details": "stock"
}
]
}
As for but it showing me all of the products I want to show the same category products in the same div you need to change the following in your iterator code:
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var Categories;
Categories = myObj.Categories;
Object.keys(Categories).forEach(function(key) {
var Products = Categories[key];
// create your div here
var div = document.createElement('div');
div.innerHTML = '';
Products.forEach(element => {
//[! remove this] var div = document.createElement('div');
//[! concatenate instead of assigning it] div.innerHTML = "html codes here";
div.innerHTML += 'your html here';
div.setAttribute('class', 'category-type');
Why? Because in your code you are reassigning the HTML to a new div for every product. Since you want to display all the information for all products under each category in a single div, your code would not work as expected.
2
solved Looping over JSON nested array in JavaScript