Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!