const A = [{category: "Walls", id: "1"}, {category: "Walls", id: "2"}]; //first array
const B = [{category: "Window", id: "3"}, {category: "Walls", id: "4"}]; //second array
const C = [{category: "Walls", id: "5"}, {category: "Floor", id: "6"}]; //three array
const D = [{category: "Walls", id: "5"}, {category: "Walls", id: "6"}]; //four array
<details>
<summary>Walls</summary>
<button class="A">1</button>
<button class="A">2</button>
<button class="B">4</button>
<button class="B">5</button>
<button class="C">5</button>
<button class="D">6</button>
</details>
<details>
<summary>Window</summary>
<button class="B">3</button>
</details>
<details>
<summary>Floor</summary>
<button class="D">6</button>
</details>
const A = [{category: "Walls", id: "1"}, {category: "Walls", id: "2"}];
const B = [{category: "Window", id: "3"}, {category: "Walls", id: "4"}];
const C = [{category: "Walls", id: "5"}, {category: "Floor", id: "6"}];
const D = [{category: "Walls", id: "5"}, {category: "Walls", id: "6"}];
let newArr = [];
newArr['Walls'] = [];
newArr['Window'] = [];
newArr['Floor'] = [];
const allArr = {'A':A,'B':B,'C':C,'D':D};
for (let key in allArr) {
allArr[key].forEach(function (item) {
let tempItem = {'id': item.id, 'class': key};
newArr[item.category].push(tempItem);
});
}
for (let key in newArr) {
let section = $('<details></details>');
let summary = $('<summary>'+key+'</summary>');
section.appendTo('body');
section.append(summary);
newArr[key].forEach(function (item) {
console.log(item);
let newElement = $('<button class="'+item.class+'">'+item.id+'</button>');
section.append(newElement);
})
}
function makeDOM(html) { //Формируем DOM на основе структуры
for(let category in html) {
let det = document.createElement('details');
let cat = document.createElement('summary');
cat.innerText = category;
det.appendChild(cat);
html[category].forEach(o=>{
let button = document.createElement('button');
button.className = o.k;
button.innerText = o.id;
det.appendChild(button);
});
document.body.appendChild(det);
}
}
let html = {};
function makeButton(o) { //Формируем структуру
if (typeof o !== "object") return;
if (o instanceof Array) {
let k = o[o.length-1];
o.forEach(e=>{e.k=k,makeButton(e)});
return;
}
if (!o.id) {
for(let k in o) makeButton(o[k].concat([k]));
return;
}
let summary;summary = html[o.category] ||(summary = html[o.category] = []);
summary.push({k:o.k,id:o.id});
}
window.addEventListener('DOMContentLoaded',e=>{
makeButton({A:A,B:B,C:C,D:D});
makeDOM(html);
});