To populate a <select> dropdown with <option> elements from a JavaScript object using jQuery, iterate over the object’s own enumerable entries safely (using Object.entries(sourceObject) or a Map), validate inputs and guard the target <select> jQuery collection, build $("<option>") elements with .val(key) and .text(label) (never innerHTML/HTML concatenation from raw strings), optionally clear existing options first and preserve or apply a selected value, and .trigger("change") when dependent listeners need notification.
1. Populating a <select> Safely from a Plain Object with .val() and .text()
Validate the jQuery <select> collection and the source object, clear stale options when requested, append each <option> using .val() and .text(), and apply an optional default selection:
// Populate a <select> dropdown with <option> items from a plain object using jQuery
function populateSelectFromObject($select, entriesObject, {
clearExisting = true,
placeholderText = null,
selectedValue = null,
triggerChange = false
} = {}) {
if (typeof $ === "undefined" || !$select || $select.length === 0) {
throw new TypeError("Expected a non-empty jQuery <select> collection.");
}
if (entriesObject === null || typeof entriesObject !== "object" || Array.isArray(entriesObject)) {
throw new TypeError("Expected entriesObject to be a non-null plain object.");
}
if (typeof clearExisting !== "boolean" || typeof triggerChange !== "boolean") {
throw new TypeError("Expected clearExisting and triggerChange to be booleans.");
}
try {
const optionNodes = [];
if (typeof placeholderText === "string" && placeholderText.trim().length > 0) {
const $placeholder = $("<option>")
.val("")
.text(placeholderText.trim());
optionNodes.push($placeholder.get(0));
}
for (const [key, label] of Object.entries(entriesObject)) {
if (label === null || label === undefined) {
continue;
}
const optionText = typeof label === "object" && label !== null && "label" in label
? String(label.label)
: String(label);
const isDisabled = typeof label === "object" && label !== null && Boolean(label.disabled);
const $option = $("<option>")
.val(String(key))
.text(optionText);
if (isDisabled) {
$option.prop("disabled", true);
}
optionNodes.push($option.get(0));
}
if (clearExisting) {
$select.empty();
}
$select.append(optionNodes);
if (selectedValue !== null && selectedValue !== undefined) {
$select.val(String(selectedValue));
}
if (triggerChange) {
$select.trigger("change");
}
return optionNodes.length;
} catch (error) {
throw new Error(`Failed populating <select> from object: ${error.message}`);
}
}
// Example usage:
// const statusMap = {
// pending: "Pending Review",
// approved: "Approved",
// rejected: "Rejected"
// };
// populateSelectFromObject($("#status-select"), statusMap, {
// clearExisting: true,
// placeholderText: "-- Select status --",
// selectedValue: "approved",
// triggerChange: true
// });
- Always set visible text with
.text(...)rather than building<option value="...">...</option>HTML strings: Escapes special characters automatically and prevents markup injection. - Batch DOM insertions into an array before calling
.append(...): Reduces repeated layout/reflow work compared to calling.append()inside every loop iteration.
2. Preserving Insertion Order, Numeric Keys, and Map Alternatives
JavaScript objects reorder integer-like string keys ("0", "1", "42") in ascending numeric order ahead of other string keys during Object.entries(), and can collide with prototype properties if not guarded—use a Map when exact insertion order or non-string keys matter:
// Populate a <select> from a Map to preserve exact insertion order without integer-key reordering
function populateSelectFromMap($select, orderedEntriesMap, { selectedValue = null } = {}) {
if (typeof $ === "undefined" || !$select || $select.length === 0) {
throw new TypeError("Expected a non-empty jQuery <select> collection.");
}
if (!(orderedEntriesMap instanceof Map)) {
throw new TypeError("Expected orderedEntriesMap to be a Map instance.");
}
try {
const fragment = document.createDocumentFragment();
for (const [key, label] of orderedEntriesMap.entries()) {
if (key === null || key === undefined || label === null || label === undefined) {
continue;
}
const optionEl = document.createElement("option");
optionEl.value = String(key);
optionEl.textContent = String(label);
fragment.appendChild(optionEl);
}
$select.empty();
$select.append(fragment);
if (selectedValue !== null && selectedValue !== undefined) {
$select.val(String(selectedValue));
}
return orderedEntriesMap.size;
} catch (error) {
throw new Error(`Failed populating <select> from Map: ${error.message}`); } } // Example usage: // const priorityMap = new Map([ // ["2", "Medium"], // ["1", "High"], // ["3", "Low"] // ]); // populateSelectFromMap($("#priority-select"), priorityMap, { selectedValue: "1" }); - **`Object.entries({ "2": "Medium", "1": "High" })` sorts `"1"` before `"2"`:** `Map` preserves exact insertion order regardless of numeric-looking keys. - **Verify `selectedValue` exists among the rendered options:** If `$select.val("missing")` is set on a single `<select>`, the selection remains unchanged or blank rather than throwing.
3. Dependent Dropdowns, Empty States, and Event Lifecycle
When populating cascading dropdowns (such as Country -> State/Province or Category -> Subcategory):
- Disable empty or unpopulated child dropdowns: If an object has zero usable entries, clear the
<select>, add a disabled placeholder option, and set.prop("disabled", true)until valid options load. - Avoid infinite
changeloops in cascading dropdowns: When a parentchangehandler repopulates a child<select>, only triggerchangeon the child when its value actually changes or downstream listeners require it. - Guard against missing DOM elements in shared page scripts: Checking
$select &&$select.length > 0prevents runtime errors on pages where a shared script runs without that specific<select>.
