How can I make redundant and unnecessary sentences shorthand in javscript?
My code is below.
//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;
}
By the way, the code is redundant and less readable.
I'm wondering how I can change this as a best practice!
Best Regards!
I would probably approach it with the following method.
querySelectorAll.property object, iterate over them, and then for each create a selector from the property key, query that element, and set the checked status.// 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">