Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
How to get comma separated JSON data on its on line?

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.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you have control of the API design, something like

{
  title: 'Company Name',
  markets: [
    { id: 4, name: 'Asia' },
    { id: 4, name: 'US' }
  ]
}

would make usage easier and more clear.

Given the example though, and making a couple assumptions:

  1. market names are unique
  2. market_ids is ordered same as markets including duplication

this should work

$
  .ajax({
    method: 'GET',
    url: 'http://localhost:9001/api/directory',
  })
  .done((data, status, xhr) => {
    const marketSelect = $(".directory-input.market");
    const labels = Array.from(new Set(data.markets.split(', ')));
    const ids = Array.from(new Set(data.market_ids.split(', ')));
    
    labels.forEach(
        (label, idx) => 
            marketSelect.append(`<option value="${ids[idx]}" class="market-option">${label}</option>`)
    );
  });

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

const data = { 
"title": "Company Name",
"markets": "US, Asia, Asia",
"market_ids": "4, 5, 5"
};

const marketSelectEl = document.getElementById('market-select');
const markets = Array.from(
  new Set(data.markets.split(',').map(m => m.trim()))
  );
const market_ids =  Array.from(
  new Set(data.markets.split(',').map(m => m.trim()))
  );
const marketOptions = markets
  .map((marketName, index) => {
    const optionEl = document.createElement('option');
    optionEl.value = market_ids[index];
    optionEl.innerText = marketName;
    return optionEl;
  })
  
  ;

marketOptions.forEach(el => marketSelectEl.append(el));
<select id="market-select" style="width: 200px;">
</select>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda