To convert a string into an array of options, you can use the following method:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsToArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsToArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
An alternative method is to parse the string using the DOMParser:
function optionsToArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
This will create an array with pairs of ID and text values like so:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
If you prefer pairs of ID and text as separate arrays, you can modify the function as follows:
function optionsToArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
The above code snippet can be further simplified to:
function optionsToArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}