我有一個物件陣列,它們都遵循相同的格式和另一個物件陣列
使用以下代碼,我可以毫無問題地生成副標題。但是,我想要的是將生成的服務分開的副標題。小標題分隔基于services[k].category.
到目前為止,這是我所擁有的,但是它不起作用。副標題生成沒有問題,但其余的不起作用:
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 class="services"></div>
如果一切正常,最終結果應該如下所示:

uj5u.com熱心網友回復:
1. 讓我們按類別對我們的初始服務陣列進行分組:
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 是一個物件,其中鍵是服務類別,值是分配給類別的服務陣列:
{
service1: [ { name: '...', ... }, ... ],
service2: [ { name: '...', ... }, ... ],
service3: [ { name: '...', ... }, ... ],
...
}
2、現在可以對每個類別的服務進行一一處理:
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>';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396444.html
標籤:javascript 查询 数组
