JavaScript: how to get values โ€‹โ€‹from a multidimensional array?

I am trying to get values โ€‹โ€‹from a multidimensional array. This is what I still have. I need a value of 99 and an image when I select the first parameter in an array, for example. "Billy Joel."

var concertArray = [ ["Billy Joel", "99", "equal.png"], ["Bryan Adams", "89", "higher.png"], ["Brian Adams", "25", "lower.png"] ]; function populate(){ for(i = 0; i < concertArray.length; i++){ var select = document.getElementById("test"); select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]); } } 
+6
source share
4 answers

You can try to convert a multidimensional array into an array of such objects:

 var concertArray = [ {name: "Billy Joel", value: 99, image: "equal.png"}, {name: "Bryan Adams", value: 89, image: "higher.png"}, {name: "Brian Adams", value: 25, image: "lower.png"} ]; 

Then you can access the elements in the array, just like regular objects:

 var concertName = concertArray[0].name; var concertPrice = parseFloat(concertArray[0].value); var concertImage = concertArray[0].image; 
+14
source

99 => concertArray[i][1] image => concertArray[i][2]

+5
source

AFAIK, the Option constructor accepts only two arguments, text and value . If you want to transfer more data, I suggest you use the HTML5 data API:

 var opt = new Option(concertArray[i][0], concertArray[i][1]); opt.setAttribute('data-image', concertArray[i][2]); select.options[select.options.length] = opt; 

Then you can capture it with getAttribute('data-image')

0
source

You can access the values โ€‹โ€‹using 2 for loops, as shown below.

 var concertArray = [ ["Billy Joel", "99", "equal.png"], ["Bryan Adams", "89", "higher.png"], ["Brian Adams", "25", "lower.png"] ]; function populate(){ for(i=0;i<arr.length;i++) { for(j=0;j<arr[i].length;j++) { console.log(arr[i][j]); } } } 
0
source

Source: https://habr.com/ru/post/913863/


All Articles