I want to change all the options of a select element when user clicks on the button. However, the new data appended inside the select tags don't follow their orders in the newOptions variable. It puts all the values with keys leading with 0 to the bottom of the list although they are declared and should be on the top. How can I fix this issue?
Expected:
<select name="car" id="car">
<option value="0">00</option>
<option value="5">05</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
Got
<select name="car" id="car">
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
<option value="0">00</option>
<option value="5">05</option>
</select>
function change() {
$("#car").empty();
newOptions = {
"00": 0,
"05": 5,
"15": 15,
"30": 30,
"45": 45
}
for (const [k, v] of Object.entries(newOptions)) {
$("#car").append($("<option></option>").attr("value", v).text(k));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="car" id="car">
<option value="00">Toyota</option>
<option value="10">BMW</option>
<option value="20">Honda</option>
</select>
<input type="submit" onclick="change()" value="Change select options">