Как полное отображение данных, а затем показать их в форме дереваJavascript

Форум по Javascript
Ответить
Anonymous
 Как полное отображение данных, а затем показать их в форме дерева

Сообщение Anonymous »

Я хочу показать сумму каждого человека и суммы сумм от его детей вместе.
// Function to transform the flat list of sponsors into a tree structure
function buildSponsorTree(sponsors, amn) {
console.log(sponsors, amn);
const sponsorMap = new Map();

// Map each sponsor by its ID for easy access
sponsors.forEach(sponsor => {
sponsorMap.set(sponsor.id, {...sponsor, children: []});
});

const rootSponsors = [];
// Build the tree structure where sponsor_id is the child and id is the parent
sponsors.forEach(sponsor => {
if(sponsor.sponsor_id !== -1) {
// If the sponsor has a sponsor_id, it's a child of another sponsor (id is parent)
const parent = sponsorMap.get(sponsor.sponsor_id);
if(parent) {
parent.children.push(sponsorMap.get(sponsor.id));
}
} else {
// If sponsor_id is null, it is a root sponsor (top-level)
rootSponsors.push(sponsorMap.get(sponsor.id));
}
});
const amountMap = new Map();
amn.forEach(amount => {
amountMap.set(amount._id, amount);
});
function calculateTotalAmount(sponsor) {
// Calculate total amount for this sponsor
let total = sponsor.amount || 0;

// Recursively calculate the total for all children
sponsor.children.forEach(child => {
total += calculateTotalAmount(child);
});

// Add the total amount to the sponsor
sponsor.totalAmount = total;
return total;
}
// Calculate total amount for all root sponsors
rootSponsors.forEach(sponsor => {
const amt = amountMap.get(sponsor.id);
if(amt) {
sponsor.amount = amt.totalAmount;
} else {
sponsor.amount = 0;
}
calculateTotalAmount(sponsor); // Calculate total for the sponsor and descendants
});
return rootSponsors; // Return the root nodes which form the tree
}

// Function to recursively render the sponsor tree
function renderSponsorTree(sponsors) {
let html = '
  • ';
    sponsors.forEach(sponsor => {
    console.log(sponsor.totalAmount, sponsor.amount);
    html += `
  • ${sponsor.name} (ID: ${sponsor.id}) Amount - ${sponsor.amount} (TotalAmount - ${sponsor.totalAmount})
    ${sponsor.children.length > 0 ? renderSponsorTree(sponsor.children) : ''}

    `;
    });
    html += '
';
return html; // Return the HTML representation of the tree
}

// Fetch sponsor data from the server and process it into a tree structure
window.onload = function() {
axios.get("http://localhost:5000/show").then((response) => {
const sponsors = response.data[0]; // Extract the sponsor data from the response
const amn = response.data[1];
const sponsorTree = buildSponsorTree(sponsors, amn); // Build the tree from the flat list
const treeHtml = renderSponsorTree(sponsorTree); // Render the tree into HTML
console.log(sponsorTree);
document.getElementById("show").innerHTML = treeHtml; // Display the tree on the page
}).catch((error) => {
console.error('Error fetching data:', error); // Handle any errors
alert('Error loading sponsor data.');
});
};

< /code>
ниже вывод: < /p>
Raj (ID: 1) Amount - 500 (TotalAmount - 500)
Ali (ID: 2) Amount - undefined (TotalAmount - 0)
Riya (ID: 3) Amount - undefined (TotalAmount - 0)
Piya (ID: 4) Amount - undefined (TotalAmount - 0)
Sana (ID: 5) Amount - undefined (TotalAmount - 0)
Dani (ID: 6) Amount - undefined (TotalAmount - 0)
Uri (ID: 7) Amount - undefined (TotalAmount - 0)
Pari (ID: 10) Amount - undefined (TotalAmount - 0)
Lara (ID: 11) Amount - undefined (TotalAmount - 0)
Rai (ID: 16) Amount - undefined (TotalAmount - 0)
abv (ID: 21) Amount - undefined (TotalAmount - 0)
Isha (ID: 14) Amount - undefined (TotalAmount - 0)
Jass (ID: 23) Amount - undefined (TotalAmount - 0)
Faliz (ID: 9) Amount - undefined (TotalAmount - 0)
Ravi (ID: 15) Amount - undefined (TotalAmount - 0)
Harsh (ID: 18) Amount - undefined (TotalAmount - 0)
Jake (ID: 20) Amount - undefined (TotalAmount - 0)
Lily (ID: 8) Amount - undefined (TotalAmount - 0)
Daya (ID: 12) Amount - undefined (TotalAmount - 0)
Goli (ID: 22) Amount - undefined (TotalAmount - 0)
Navi (ID: 13) Amount - undefined (TotalAmount - 0)
Isha (ID: 17) Amount - undefined (TotalAmount - 0)
Jay (ID: 19) Amount - undefined (TotalAmount - 0)
< /code>
Сумма для первого идентификатора является правильной, но TotalAmount должна быть суммой всех его детей, в данном случае, сумме всего дерева, поэтому значение 500 выше неверно и если в let total = sponsor.amount || 0; || 0 пропущено, затем TotalAmount возвращает NAN или не определен.app.get("/show", async (req, res) => {
try {
const data = await sponsorModel.find();
const amount = await amountModel.aggregate([
{
$group:
{
_id: "$id",
totalAmount: { $sum: "$amount" }
}
}
]);
res.status(200).json([data, amount]);
} catch (error) {
res.status(500).json(error);
}
});

Ниже приведен формат JSON [Data, Summ] Здесь идентификатор данных соответствует сумме _ID, а сумма TotalAmount-это то, что следует показать для Sponsor.Amount и Sponsor.totalAmount на фронтенде-это то, что должно быть суммой всех детей


Подробнее здесь: https://stackoverflow.com/questions/795 ... -of-a-tree
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»