Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
How to get element of an array stored in one value

I wonder if there is a way to get a certain element of an array, which is stored in a single value. Sounds weird, I know, but this is my problem:

HTML

<select id="select">
    <option value='{"array":["a","b"]}'>Option</option>
</select>

<button onClick="getArrayIndex()">Button</button>

--> I got one array with two elements (a and b) stored isnide one value in an option tag.

JS

function getArrayIndex() {
    alert(option.value[0]);
}

So what I need is that the alert message displays only one element of the array, I hope this is somehow possible, thanks for answers! As you can see I tried to display only element 0, in this case "a", but it doesn't work. I also tried these:

alert(option.value.array[0]);
alert(option.value.array(0));
alert(option.value(0));
alert(option.value.[0]);

...and so on. But none of these work.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your value is a string containing JSON defining an object containing an array property with an array, rather than actually being an array. To use just the first element in that array, you need to parse the JSON into the object and array, then access the array from the object and get its first element:

alert(JSON.parse(option.value).array[0]); // "a"

Note that your getArrayIndex function currently uses an option identifier that doesn't appear to be defined anywhere. If you want to use the currently-selected value in the select, then:

function getArrayIndex() {
    const select = document.getElementById("select");
    const value = select.value;
    if (value) {
        alert(JSON.parse(value).array[0]);
    }
}

Side note: I would xyz-attribute-style event handlers. Instead, hook up the event handler using modern techniques (such as addEventListener). Also beware that the default type of the button element is "submit", so if that button is in a form, by default it will submit the form.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda