Untitled
function transformData(input) { try { if (!input || typeof input !== 'object' || !input.data) { throw new Error("Invalid input format. Expected an object with a 'data' property."); } const { labels, data } = input.data; if (!Array.isArray(labels) || !Array.isArray(data) || labels.length !== data.length) { throw new Error("Invalid data format. 'labels' and 'data' must be arrays of the same length."); } const stateMapping = [ { id: 'AP', state: 'Andhra Pradesh' }, { id: 'AR', state: 'Arunachal Pradesh' }, { id: 'AS', state: 'Assam' }, { id: 'BR', state: 'Bihar' }, { id: 'CT', state: 'Chhattisgarh' }, { id: 'GA', state: 'Goa' }, { id: 'GJ', state: 'Gujarat' }, { id: 'HR', state: 'Haryana' }, { id: 'HP', state: 'Himachal Pradesh' }, { id: 'JH', state: 'Jharkhand' }, { id: 'KA', state: 'Karnataka' }, { id: 'KL', state: 'Kerala' }, { id: 'MP', state: 'Madhya Pradesh' }, { id: 'MH', state: 'Maharashtra' }, { id: 'MN', state: 'Manipur' }, { id: 'ML', state: 'Meghalaya' }, { id: 'MZ', state: 'Mizoram' }, { id: 'NL', state: 'Nagaland' }, { id: 'OD', state: 'Odisha' }, { id: 'PB', state: 'Punjab' }, { id: 'RJ', state: 'Rajasthan' }, { id: 'SK', state: 'Sikkim' }, { id: 'TN', state: 'Tamil Nadu' }, { id: 'TS', state: 'Telangana' }, { id: 'TR', state: 'Tripura' }, { id: 'UK', state: 'Uttarakhand' }, { id: 'UP', state: 'Uttar Pradesh' }, { id: 'WB', state: 'West Bengal' }, { id: 'AN', state: 'Andaman and Nicobar Islands' }, { id: 'CH', state: 'Chandigarh' }, { id: 'DN', state: 'Dadra and Nagar Haveli' }, { id: 'DD', state: 'Daman and Diu' }, { id: 'DL', state: 'Delhi' }, { id: 'JK', state: 'Jammu and Kashmir' }, { id: 'LA', state: 'Ladakh' }, { id: 'LD', state: 'Lakshadweep' }, { id: 'PY', state: 'Puducherry' } ]; const stateMap = new Map(stateMapping.map(s => [s.id, s.state])); return labels.map((id, index) => { if (!stateMap.has(id)) { throw new Error(`State code '${id}' not found in the mapping.`); } return { id, state: stateMap.get(id), value: parseInt(data[index], 10) }; }); } catch (error) { console.error("Error processing data:", error.message); return []; } } // Example usage: const inputData = { "data": { "labels": ["AP", "AR", "AS", "BR", "CT", "GA", "GJ", "HR", "HP", "JH", "KA", "KL", "MP", "MH", "MN", "ML", "MZ", "NL", "OD", "PB", "RJ", "SK", "TN", "TS", "TR", "UK", "UP", "WB", "AN", "CH", "DN", "DD", "DL", "JK", "LA", "LD", "PY"], "data": ["33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33"] } }; console.log(transformData(inputData));
Leave a Comment