У меня есть
код, который создаёт выпадающий список. Мне нужно добавить к каждой кнопке класс соответственно тому в каком массиве находится id этой кнопки. Т.е. к кнопкам из массива "A" и "B" нужно добавить класс "A" и "B", а к кнопки из массива "C" и "D" можно добавить общий класс.
const A = [
{ category: "Walls", id: "1", symbol: "Wall_102", family: "Basic Walls" },
{ category: "Walls", id: "2", symbol: "Wall-Ext_102", family: "Basic Walls" }
];
const B = [
{
category: "Window",
id: "3",
symbol: "Window-Ext_102",
family: "Basic Window"
},
{
category: "Walls",
id: "4",
symbol: "Wall-Other-102",
family: "Other Walls"
}
];
const C = [
{ category: "Walls", id: "5", symbol: "Wall-Ext_102", family: "Basic Walls" },
{ category: "Floor", id: "6", symbol: "Floor-Ext_102", family: "Basic Floor" }
];
const D = [
{ category: "Walls", id: "5", symbol: "Wall-Ext_102", family: "Basic Walls" },
{ category: "Walls", id: "6", symbol: "Wall-Ext_102", family: "Basic Walls" }
];
const data = [...A, ...B, ...C, ...D];
const result = data.reduce(
(acc, curr) => {
const { category, family, symbol, id } = curr;
acc.category[category] = acc.category[category] || { family: {} };
acc.category[category].family[family] = acc.category[category].family[
family
] || { symbol: {} };
acc.category[category].family[family].symbol[symbol] = acc.category[
category
].family[family].symbol[symbol] || { id: [] };
acc.category[category].family[family].symbol[symbol].id.push(id);
return acc;
},
{ category: {} }
);
let html = "";
for (let categoryKey in result.category) {
html += `<details><summary>${categoryKey}</summary>`;
for (let familyKey in result.category[categoryKey].family) {
html += `<details><summary>${familyKey}</summary>`;
for (let symbolKey in result.category[categoryKey].family[familyKey]
.symbol) {
let btn =
result.category[categoryKey].family[familyKey].symbol[symbolKey];
html += `<details><summary>${symbolKey}</summary>
${btn.id.map(id => `<button>${id}</button>`).join("")}
</details>
`;
}
html += `</details>`;
}
html += `</details>`;
}
document.body.innerHTML = html;