Marcos Belunti Marcos Belunti - 2 months ago 6
jQuery Question

Javascript - Filter array results into dropdown list

I have an array as shown below where I want to filter the data and insert the filtered list into a dropdown list.

Here is the data:

{"people":[
{
"id":"100",
"name":"name 1",
"desc":"desc 1",
"class": "a"
},
{
"id":"192",
"name":"name 2",
"desc":"desc 2",
"class": "b"
},
{
"id":"324",
"name":"name 3",
"desc":"desc 3",
"class": "b"
},
{
"id":"324",
"name":"name 4",
"desc":"desc 4",
"class": "a"
},
{
"id":"324",
"name":"name 5",
"desc":"desc 5",
"class": "a"
}
]}


What I now need to do is to add the array with "class" of "a" and then insert the id's of these into a dropdown list like:

$('#myselect').append($('<option>').text(value.id).attr('value', value.id));


How can I do this?

Answer

Here is an solution using Array.filter()

var obj = {
  "people": [{
    "id": "100",
    "name": "name 1",
    "desc": "desc 1",
    "class": "a"
  }, {
    "id": "192",
    "name": "name 2",
    "desc": "desc 2",
    "class": "b"
  }, {
    "id": "324",
    "name": "name 3",
    "desc": "desc 3",
    "class": "b"
  }, {
    "id": "324",
    "name": "name 4",
    "desc": "desc 4",
    "class": "a"
  }, {
    "id": "324",
    "name": "name 5",
    "desc": "desc 5",
    "class": "a"
  }]
};

obj.people.filter(function(val) {
  if (val.class == "a") {
    $('#myselect').append($('<option>').text(val.id).attr('value', val.id));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="myselect">
</select>