Search code examples
javascriptjqueryjsondropdownbox

Fill tree json data to dropdown box


I have json data in tree format:

[
  {
    "beer_names": [
      "Apple Ale",
      "Bad Seed Pumpkin Ale"
    ],
    "brewery": "Basil T's Brew Pub and Italian Grill"
  },
  {
    "beer_names": [
      "5 C's IPA",
      "Bottle Rocket IPA",
      "Kate The Great Russian Imperial Stout",
      "Wheat Wine"
    ],
    "brewery": "Portsmouth Brewery"
  },
  {
    "beer_names": [
      "Black Forest Dunkelweizen",
      "Equinox E.S.B.",
      "Evolutionary IPA",
      "G.E. Lite",
      "Nut Brown",
      "Red",
      "Smoked Porter"
    ],
    "brewery": "Glen Ellyn Sports Brew"
  }
]

So I want to fill this data to Dropdown box like this:

--Basil T's Brew Pub and Italian Grill
--------Apple Ale
--------Bad Seed Pumpkin Ale
--Portsmouth Brewery
--------5 C's IPA
--------Bottle Rocket IPA
--------Wheat Wine
--------Kate The Great Russian Imperial Stout
--Glen Ellyn Sports Brew
--------Black Forest Dunkelweizen
--------Equinox E.S.B.
--------Evolutionary IPA
--------G.E. Lite
--------Nut Brown
--------Red
--------Smoked Porter

Or a tree view allow for select value name of child equipment?


Solution

  • Here you are:

    var data = [{
      "beer_names": [
        "Apple Ale",
        "Bad Seed Pumpkin Ale"
      ],
      "brewery": "Basil T's Brew Pub and Italian Grill"
    }, {
      "beer_names": [
        "5 C's IPA",
        "Bottle Rocket IPA",
        "Kate The Great Russian Imperial Stout",
        "Wheat Wine"
      ],
      "brewery": "Portsmouth Brewery"
    }, {
      "beer_names": [
        "Black Forest Dunkelweizen",
        "Equinox E.S.B.",
        "Evolutionary IPA",
        "G.E. Lite",
        "Nut Brown",
        "Red",
        "Smoked Porter"
      ],
      "brewery": "Glen Ellyn Sports Brew"
    }];
    $.each(data, function(index, value) {
      var str = '<optgroup label="' + value["brewery"] + '">';
      $.each(value['beer_names'], function(index, value) {
        str += '<option value="' + value + '">' + value + '</option>';
      });
      str += '</select>';
      $('select').append(str);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select></select>

    Hope this helps.