Angular 10中如何将distYearMonths的月份名称转为对应数字
Hey there, let's work through this together. You need to swap those 3-letter month abbreviations with their corresponding numeric values while keeping your original object structure intact. Here's a straightforward, Angular 10-friendly approach:
Step 1: Create a Month Mapping Reference
First, we'll make a simple object that maps each month abbreviation to its numeric equivalent—this is the core of our conversion logic:
const monthAbbrToNum: { [key: string]: number } = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 };
Step 2: Build the Conversion Function
Next, we'll write a function that processes your original distYearMonths object, converts every month abbreviation, and returns the updated data in the exact same structure:
// Your original data structure const distYearMonths = { 2018: ["Oct", "Sep", "Dec", "Nov"], 2019: ["Jan", "Jul", "Jun", "Nov", "Oct", "Sep", "Apr", "Aug", "Dec", "Feb", "Mar", "May"], 2020: ["Feb", "Jan", "Mar", "May", "Apr", "Jun"] }; function convertMonthAbbrs(yearMonths: { [key: string]: string[] }): { [key: string]: number[] } { // Convert the object to [year, month array] pairs, process each, then convert back to object return Object.fromEntries( Object.entries(yearMonths).map(([year, monthAbbrs]) => { // Map each abbreviation to its numeric value const numericMonths = monthAbbrs.map(abbr => monthAbbrToNum[abbr]); return [year, numericMonths]; }) ); } // Run the conversion const convertedYearMonths = convertMonthAbbrs(distYearMonths); console.log(convertedYearMonths);
How This Works
Object.entries(yearMonths)splits your original object into an array of[year, monthAbbrs]pairs, making it easy to loop through each year's data.monthAbbrs.map(abbr => monthAbbrToNum[abbr])converts every abbreviation in the array to its matching number using our reference table.Object.fromEntries(...)turns the processed array of pairs back into an object, so your original structure stays exactly the same.
Optional: Add Fault Tolerance
If there's a chance your data might include invalid month abbreviations, you can add a fallback value to avoid undefined in your result:
const numericMonths = monthAbbrs.map(abbr => monthAbbrToNum[abbr] || 0); // Fallback to 0 for invalid entries
This will give you the exact output you need—same object shape, just with month numbers instead of abbreviations.
内容的提问来源于stack exchange,提问作者Pruthvi sai

