寻求满足多条件的JSON转换最优代码实现方案
Cleaner, More Maintainable Approach for Your JSON Transformation
Nice work getting a functional solution up and running! Let's refactor this code to make it more readable, reusable, and robust. Here's an optimized take that addresses your requirements while keeping things clean:
First, Tweak the HTML (for Reliable DOM Targeting)
Let's add an ID to the textarea so we can grab it reliably without relying on tag order:
<div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Comments</h5> </div> <div class="modal-body"> <textarea id="commentsInput" rows="3" cols="50"></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" onclick="transformJson('approve')">Accept</button> <button type="button" class="btn btn-primary" onclick="transformJson('reject')">Reject</button> </div> </div> </div>
Optimized JavaScript Code
We'll split logic into small, single-purpose functions, avoid redundant checks, and use modern JS features for clarity:
// Cache the textarea element once (instead of querying DOM on every button click) const commentsInput = document.getElementById('commentsInput'); // Helper function to format dates to YYYY-MM-DD with leading zeros const formatDate = (dateStr) => { const date = new Date(dateStr); // Use padStart to ensure 2-digit months/days (fixes edge case for single-digit values) return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; }; // Helper to map button action to status code (cleaner than multiple if-else checks) const getStatusFromAction = (action) => { const statusMap = { approve: 'A', reject: 'R' }; return statusMap[action] || ''; // Fallback to empty string if action is unknown }; function transformJson(action) { // Original JSON data (could easily replace with API fetch logic here) const originalJson = { "Reference No":"101", "Date Of Reporting":"2019/04/29", "Status":"", "Comments":"", "Organization Name":"ABC" }; // Create a copy of the original JSON, then update only the fields we need const transformedJson = { ...originalJson, // Update Comments with textarea value Comments: commentsInput.value, // Update Status based on button action Status: getStatusFromAction(action) }; // Handle date fields: format any keys containing "date" (case-insensitive) Object.keys(transformedJson).forEach(key => { if (key.toLowerCase().includes('date')) { transformedJson[key] = formatDate(transformedJson[key]); } }); console.log(transformedJson); // You can return transformedJson here or send it directly to your API }
Key Improvements Explained
- DOM Element Caching: We grab the textarea once outside the function instead of querying the DOM on every button click, which boosts performance.
- Single-Purpose Helpers:
formatDateandgetStatusFromActionmake the main function cleaner and let you reuse these utilities elsewhere in your codebase if needed. - Modern Object Spread: Using
...originalJsoncreates a copy of the original data in one line, so we don't have to manually loop through every key just to copy values. We only overwrite the fields we need to change. - Robust Date Formatting:
padStartensures months and days are always 2 digits (e.g.,04instead of4), fixing a potential edge case in your original code. - Status Mapping: Using an object (
statusMap) instead of multipleif-elsechecks makes it trivial to add new statuses later (just update the map). - Readability: The flow is now linear and easy to follow: copy original data → update comments/status → format dates → output.
内容的提问来源于stack exchange,提问作者Anil Kumar Moharana
相关产品推荐
相关产品推荐

