jquery – How to traverse through an array of JSON in javascript? and use it to populate element

I have this array of JSON and I want to loop through them and use it to fill up my option element.

Sample Array:

var myOptionData = [
          {fooValue:"1", fooText:"option A"},
          {fooValue:"2", fooText:"option B"},
          {fooValue:"3", fooText:"option C"}
] 

I did use this method:

var fields="";

 fields += "</select >";

        fields += "<option  value="0"></option>";
        $.each(myOptionData , function (key, value) {
            fields += "<option value=" + value.fooValue + ">" + value.fooText + "</option>";
        });
        fields += "</select >";

//But I want to make it more flexible, so that I can reuse it in making another <option> from another array of JSON, like this scenario:

var myNewOptionData = [
          {myValue:"5", myText:"option E"},
          {myValue:"6", myText:"option F"},
          {myValue:"7", myText:"option G"},
          {myValue:"8", myText:"option H"}
] 

//Now I cannot use the method above

Read more here: Source link