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
2
Answers
Simply turn the whole operation into a function:
The function should be improved, as it momentarily relies on the sequence of the properties of object
o
. Maybe the property names could be checked for containing "Value" and "Text"?Here is a slight variation of my snippet, checking for parts of the property names. Now the order of the given option properties is immaterial and a selected option can also be defined by providing a property that contains "select" in its name:
Generally when making a function you should expect to receive parameters with defined keys. There’s nothing wrong with requiring objects within lists to have fooValue & fooText. However if you want to make it property-independent:
Note how jQuery isn’t necessary in this case.
Map is a function that transforms every item on your list (without modifying it)
Also if you want to ‘just specify the keys once and then reuse’ you can create partially applied functions: