JSFiddle - React, Tailwind, and code Playground
by Gunnar
HTML
<select id="select"></select>
<div id="key1"></div>
<div id="key2"></div>
JavaScript
$(document).ready(function () {
// JS object array
var groups = [{
"name": "A",
"key1": "value_a_1",
"key2": "value_a_2"
}, {
"name": "B",
"key1": "value_b_1",
"key2": "value_b_2"
}];
// create select from array
var options = "";
$.each(groups, function (idx, val) {
options += "<option id=" + val.name + (idx = 0 ? " seleted " : "") + ">Group " + val.name + "</option>";
});
$("#select").html(options);
// bind selection handler
$("#select").change(function() {
switchContent();
});
// helper gets array entry for selected option
function getSelected() {
var selected = $.grep(groups, function (val) {
return $("#select option:selected").attr("id") === val.name;
});
return selected[0];
}
// fills in content depending on selectec option
function switchContent() {
var selected = getSelected();
$("#key1").text(selected.key1);
$("#key2").text(selected.key2);
}
// initial switchContent for first display
switchContent();
});