Answer the question
In order to leave comments, you need to log in
How to distribute menu sub-items returned by reduce?
Good evening. Help me please. I have a script that collects the menu and its sub-items from the database. I send them to the client, what method should I receive them on the client to have a list view?
This function worked for me earlier, but now it is not relevant.
function makeMenuLevel(result) {
$(document).ready(() => {
return `<ul>${result.map(
item =>`<li>${item.title}${item.children ? makeMenuLevel(item.children) : ''}</li>`
).join('')}</ul>`;
})
}
let viewmenu;
connection.query('SELECT * FROM menu', (err, result) => {
if(err) {
console.error(err);
return;
}
const index = result.reduce((acc, row) => ({...acc, [row.id]: row}), {});
var menu = [];
for(const row of result) {
if(row.parent_id === 0) {
menu.push(row);
continue;
}
const parent = index[row.parent_id];
if(!parent) {
console.warn(`Undefined parent with id ${row.parent_id}`);
continue;
}
if(!parent.children) {
parent.children = [];
}
parent.children.push(row);
}
viewmenu = menu;
});
const sendMenu = ms => {
return new Promise(r => setTimeout(() => r(), ms))
}
sendMenu(200).then(() => res.send(viewmenu))
(7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
0:
children: Array(7)
0:
children: Array(12)
0:
id: 4
parent_id: 3
title: "Smallweight"
__proto__: Object
1: {id: 5, parent_id: 3, title: "Piglets"}
2: {id: 6, parent_id: 3, title: "Piglets for growing "}
3: {id: 7, parent_id: 3, title: "Culling pigs"}
4: {id: 8, parent_id: 3, title: "Culling sows"}
5: {id: 9, parent_id: 3, title : "Repairing sows"}
6: {id: 10, parent_id: 3, title: "Idle sows"}
7: {id: 11, parent_id: 3, title: "Growing pigs"}
8: {id: 12, parent_id: 3title: "Sales pig in live weight"}
9: {id: 13, parent_id: 3, title: "Culling Boars"}
10: {id: 14, parent_id: 3, title: "Cauterized Boars"}
11: {id: 15, parent_id: 3, title: " Boars "}
length: 12
__proto__: Array(0)
id: 3
parent_id: 2
title: " Live weight "
__proto__: Object
1: {id: 16, parent_id: 2, title: " Piece ", children: Array(22) }
2: {id: 39, parent_id: 2, title: " Half Carcasses ", children: Array(8)}
3: {id: 48, parent_id: 2, title: " Offal ", children: Array(34)}
4 : {id: 83, parent_id: 2, title: " Pork products ", children: Array(8)}
5: {id: 92, parent_id: 2, title: " Pork products (packaging) ",children: Array(10)}
6: {id: 170, parent_id: 2, title: "Pork other"}
length: 7
__proto__: Array(0)
id: 2
parent_id: 0
title: "Pork"
__proto__: Object
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question