Home > Enterprise >  Destructuring an array (2 columns by 3 rows) stored in a single variable into 3 separate variables J
Destructuring an array (2 columns by 3 rows) stored in a single variable into 3 separate variables J

Time:04-20

I have an array stored in a variable called data_array. When alerting, the data is shown as follows:

1 car

2 truck

3 boat

I would like to extract the second column of data based upon the first column.

If col1 = 1 then var1 = car, if col1 = 2 then var2 = truck, if col1 = 3 then var3 = boat.

Basically, I would like to assign the data in the second column to a unique variable based upon the first column. I am utilizing javascript. Any help is appreciated.

For example, I am trying something like this:

function myCallback(data_array){
    alert(data_array);

    var [col1, , var1] = data_array;  
    alert(col1   " "   var1);

}

However I only have access to the first row and the output is:

1 c

-Alan

...as you can tell, I'm pretty green but I am learning daily, here is more of my code:

  xhttp.onreadystatechange = function() {

    var xhttp = new XMLHttpRequest();

    if (this.readyState == 4 && this.status == 200) {
       data_array = this.responseText;
       alert(data_array);   // this produces what I thought was an array, it displays information from a SQL database with 2 columns and 3 rows
    }
    
    if (this.readyState == 4) {
          myCallback(this.responseText);
    }
    function myCallback(data_array){
     
    var [col1, , var1] = data_array;  
    alert(col1   " "   var1);    // this is where I cannot figure out how to pull information from subsequent rows
    
    }
  };

  xhttp.open("GET", "ajax3.php?", true);
  xhttp.send();

CodePudding user response:

let data_array = [
  [1, "car"],
  [2, "truck"],
  [3, "boat"]
]

let [col1, var1] = data_array[1]

console.log(col1, var1)

I don't know if this the soltion but this is what I got from the question

CodePudding user response:

I did my best to help you

function myCallback(data_array){
   const [col1 , col2 , col3] = data_array;
   console.log(col1 , col2 , col3);
}

const dataArray = [
  [1 , "col1"],
  [2 , "col2"],
  [3 , "col3"],
];

myCallback(dataArray)

Now if you want to access the second column of each array

console.log(col1[1])

You can also take a look at this document for more information, my friend

  • Related