I have an array of objects which all follow the same format and another array of objects
Using the following code, I am able to generate the subheadings with no issues. However what I would like to have is subheadings separating the generated services. The subheadings separations are based on the services[k].category
.
This is what I have so far, however it is not working. The subheadings generate without issue, however the rest is not working:
let categories = [{
name: "Logo and Branding"
},
{
name: "Web Design"
},
{
name: "Print"
},
{
name: "Presentations"
},
{
name: "Art & Illustration"
},
{
name: "Animation"
}
]
let services = [{
"name": "Logo",
"description": "Capture the essence of your brand with an unforgettable logo design.",
"icon": "logo.svg",
"category": "logo"
}]
function generateServices(amount) {
var content = "";
for (let q = 0; q < categories.length; q ) {
content = '<div ><div ><h2 >' categories[q].name '</h2></div></div>';
}
$('.services').html(content);
let servicesheading = $('.servicestitle');
// add the new items
for (let k = 0; k < amount; k ) {
console.log(servicesheading.html);
if (servicesheading.innerText == services[k].description) {
content = '<div ><div ><img src="img/services/SVG/' services[k].icon '"><h4>' services[k].name '</h4><p>' services[k].description '</p></div></div>';
}
}
}
generateServices(10)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div ></div>
The final outcome should look like this if all were to work:
CodePudding user response:
1. Let's group our initial array of services by category:
const services = [
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
{ name: '...', category: '...', 'description': '...', 'icon': '...' },
...
];
const servicesByCategory = services.reduce((acc,el) => {
if (acc[el.category]) acc[el.category].push(el)
else acc[el.category] = [el];
return acc;
}, {});
servicesByCategory
is an object where keys are service categories and values are arrays of services assigned to category:
{
service1: [ { name: '...', ... }, ... ],
service2: [ { name: '...', ... }, ... ],
service3: [ { name: '...', ... }, ... ],
...
}
2. Now you can process services one by one for each category:
let content = '';
for (let category in servicesByCategory) {
// Do what you want with category name
// Let's add category header as an example
content = '<div ><div ><h2 >' category '</h2></div></div>';
for (let service of servicesByCategory[category]) {
// Proccess services one-by-one as you did before
content = '<div ><div ><img src="img/services/SVG/' service.icon '"><h4>' service.name '</h4><p>' service.description '</p></div></div>';
}
}