¿Cómo puedo taquigrafiar oraciones redundantes e innecesarias en javscript?
Mi código está abajo.
//initialization document.querySelector('#categoryCheckNormal').checked = false; document.querySelector('#categoryCheckDisabled').checked = false; document.querySelector('#categoryCheckBlind').checked = false; document.querySelector('#categoryCheckEvacuation').checked = false; // If there is a classification, put a value if (res.eventData.property.normal) { document.querySelector('#categoryCheckNormal').checked = true; } else if (res.eventData.property.disabled) { document.querySelector('#categoryCheckDisabled').checked = true; } else if (res.eventData.property.blind) { document.querySelector('#categoryCheckBlind').checked = true; } else if (res.eventData.property.evacuation) { document.querySelector('#categoryCheckEvacuation').checked = true; }Por cierto, el código es redundante y menos legible.
¡Me pregunto cómo puedo cambiar esto como una mejor práctica!
¡Saludos!
Probablemente lo abordaría con el siguiente método.
querySelectorAll .property , iterar sobre ellas y luego, para cada una, crear un selector desde la clave de propiedad, consultar ese elemento y establecer el estado marcado. // Get all the inputs const inputs = document.querySelectorAll('input[type="checkbox"]'); // Iterate over them and reset them function reset() { inputs.forEach(input => input.checked = true); } reset(); // Get some data const res={eventData:{property:{normal:true,disabled:false,blind:false,evacuation:true}}}; // Get the property object const { property } = res.eventData; // Get its entries const entries = Object.entries(property); // Finally iterate over those entries and update // the inputs based the key of each entry for (const [key, value] of entries) { const selector = `[data-id="${key}"]`; const input = document.querySelector(selector); input.checked = value; } Normal: <input type="checkbox" data-id="normal"> Disabled: <input type="checkbox" data-id="disabled"> Blind: <input type="checkbox" data-id="blind"> Evacuation: <input type="checkbox" data-id="evacuation">