Advanced Daily Diet Chart Planner
Advanced Daily Diet Chart Planner
Diet Chart Preview
Calories: 0 kcal
Carbs: 0 g
Protein: 0 g
Fat: 0 g
Download as PDF
Print Chart
Download Profile & Chart as JSON
Download Profile & Chart as CSV
// Utility to convert array of objects to CSV string
function convertToCsv(arr) {
if (!arr.length) return '';
const keys = Object.keys(arr[0]);
const replacer = (_key, value) => (value === null || value === undefined) ? '' : value;
const csvRows = [
keys.join(','), // header row
...arr.map(row => keys.map(k => JSON.stringify(row[k], replacer)).join(','))
];
return csvRows.join('
');
}
// Gather user profile and meal data for export
function getExportData() {
const profile = {
name: document.getElementById('name').value.trim(),
age: document.getElementById('age').value,
gender: document.getElementById('gender').value,
weight: document.getElementById('weight').value,
height: document.getElementById('height').value,
dietaryPreference: document.getElementById('dietPref').value,
calorieTarget: document.querySelector('#chartContent p strong:nth-child(7)')?.textContent || ''
};
const meals = [];
const mealBlocks = document.querySelectorAll('.meal-block');
mealBlocks.forEach(block => {
meals.push({
mealName: block.querySelector('.meal-name').value.trim(),
foodItems: block.querySelector('.food-items').value.trim(),
calories: block.querySelector('.calories').value,
carbs: block.querySelector('.carbs').value,
protein: block.querySelector('.protein').value,
fat: block.querySelector('.fat').value
});
});
return { profile, meals };
}
// Download JSON file
document.getElementById('downloadJsonBtn').addEventListener('click', () => {
const data = getExportData();
const jsonStr = JSON.stringify(data, null, 2);
const blob = new Blob([jsonStr], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'diet-chart-profile.json';
a.click();
URL.revokeObjectURL(url);
});
{
const data = getExportData();
// Convert profile object to array of single object for uniform processing
const profileArray = [data.profile];
const profileCsv = convertToCsv(profileArray);
// Convert meals array to CSV
const mealsCsv = convertToCsv(data.meals);
// Combine CSV with separator
const combinedCsv = 'User Profile
' + profileCsv + '
Meals
' + mealsCsv;
const blob = new Blob([combinedCsv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'diet-chart-profile.csv';
a.click();
URL.revokeObjectURL(url);
});
No comments:
Post a Comment