I am retrieving data from an API that looks like this –
"title": "Company Name",
"markets": "US, Asia",
"market_ids": "4, 5"
I need to add this data to a dropdown menu like this –
<option value="4">US</option>
So I need to remove the commas and any duplicates (there will be many entries with the same market)
I was thinking something like this at first –
$.ajax({
method: 'GET',
url: 'http://localhost:9001/api/directory',
}).done(function (data, status, xhr) {
let markets = [];
$.each(data, function (index, value) {
markets.push(value.markets);
})
markets = [...new Set(markets.toString().split(','))];
for (market of markets) {
$(".directory-input.market").append(
`<option value="" class="market-option">${market}</option>`)
};
});
This works to separate the market names by comma and get rid of any duplicates, but the problem is that I can’t add the market ID to the value. I need the market ID to be accessible as well.
2
Answers
If you have control of the API design, something like
would make usage easier and more clear.
Given the example though, and making a couple assumptions:
this should work
Assuming there will be the same number of ids and markets. Note, if you are adding a a lot of options, you probaly will want to create the select itself with options as a documentFragment to avoid repaints.