How to extract data from a two-dimensional array with 2 columns and 3 rows stored in a single variable using destructuring in JavaScript

I have a variable named data_array that stores an array. The data appears as:

1 car

2 truck

3 boat

I want to extract the second column of data based on the first column.

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

Simply put, I want to assign the second column data to distinct variables based on the first column. I'm using JavaScript for this task and any assistance would be great.

Currently, I am attempting the following approach:

function myCallback(data_array){
    alert(data_array);

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

However, I can only access the first row and the output is:

1 c

-Alan

I am relatively new at this but learning every day. 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); 
  }

  if (this.readyState == 4) {
    myCallback(this.responseText);
  }

  function myCallback(data_array) {

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

  }
};

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

Answer №1

let array_data = [
  [1, "bike"],
  [2, "bus"],
  [3, "train"]
]

let [num, vehicle] = array_data[1]

console.log(num, vehicle)

I'm not sure if this is the correct answer, but this is my interpretation of the problem

Answer №2

My efforts were directed towards assisting 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)

If you wish to access the second column of each array

console.log(col1[1])

You may also refer to this resource for further details, my friend

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decompress arrays containing lists in Python

Is there a way to easily extract individual values from lists that are elements of an np.array? Here is the current output format: [[0 301227 0.863 0.456 -3.551 0.532 135.96200000000002 4 list([0.49, 0.33, 0.33, 0.28, 0.26, 0.47, 0.28, 0.29, 0.41, 0.42, ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

How can I delete the visuals and objects from my mind in Three.js?

I need to place a specific number of circles on the scene. var radius = 1; var segments = 32; var circleGeometry = new THREE.CircleGeometry( radius, segments); function generateCircles(){ //scene.remove(circle); var count=0; while (1000> count ...

There seems to be an issue with the accurate calculation of the screen width while utilizing the scrollbar-gutter

Please take note: The scrollbar-gutter: stable; property is not compatible with Safari. Additionally, the issue seems to be specific to Chrome and works fine in Firefox. I have observed some unusual behavior when attempting to position elements fixed to t ...

Encountering an npm issue while attempting to execute the command "npx create-expo-app expoApp"

I've been attempting to set up an expo project, but npm is failing to do so. It does create necessary base files like APP.js, but nothing else. Here's the error I encountered: npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\User ...

What is the best method for distinguishing newly generated unique IDs from the complete list of all IDs?

Recently, I came up with a function that can generate unique IDs: function generate_uuid($needed_ids_num = 1, int $random_bytes_length = 6) { $ids = []; while (count($ids) < $needed_ids_num) { $id = bin2hex(random_bytes($random_bytes_leng ...

Update the state by utilizing the File's onLoad function

I've been facing some challenges while trying to set the state using FileReader's onLoad function. My objective is to display multiple images and update the state accordingly. Despite extensively researching various stackoverflow threads and mak ...

Using v-for with nested objects

Have you been attempting to create a v-for loop on the child elements of the {song: "xxx"} object within the songs array? export const data = [ {id: "1", albumname: "xx", artist: "xxxx", dateadded: "xxxx", route: "xxxx", songs: [{ song : &apos ...

Attempt to retrieve node information using the useStaticQuery method in Gatsby

I am facing an issue where I am trying to retrieve information from GraphQL Gatsby using useStaticQuery, but the data returned is showing as undefined. I am confused as to why this is happening because when I check my http://localhost:8000/___graphql endpo ...

Unable to transfer file using ajax (displaying print_r($_FILES); Array ( ) )

I have encountered an issue with sending a file using XHR compared to a common form confirmation. Here is the HTML code: <form action="ajax/upload.php" method="post" name="form1" enctype="multipart/form-data" id="id1"> <input type="file" name=" ...

Image cannot be shown on HTML webpage

There seems to be an issue with the rendering of the image on the index.html page. All the necessary files, including index.html, app.js, and the image file are located in a virtual machine (VM). After successfully logging in with login.js, the page redire ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Using QML to assign global properties by invoking imported JavaScript functions

Utilizing the Universal style in my QtQuick application, I am seeking to implement a ColorDialog for adjusting the accent color. My current setup looks like this: ColorDialog { id: accChooser title: "Please choose a color" onAcce ...

Tips on expanding the space between words in a scrolling "marquee" text

Looking for some assistance with my jQuery project involving a horizontal scrolling "marquee" text. I am currently trying to adjust the size of the gap between the phrases in the marquee. Here is an example with the phrase "HEY THERE". jQuery(document ...

What is the process for duplicating a div container when a button is clicked?

http://jsfiddle.net/TDmRv/1/ My Goal: I aim to have the input text wrapped in a div with the id "theDiv" every time it is added to the page. This way, the text will be displayed within multiple dynamically created divs. Further Explanation: Essentially, ...

Is it possible to swap squares for circles in a Three.js PointCloud?

Currently, I am loading a .ply file using PLYLoader in three.js and displaying it as a PointCloud. Here is the code snippet: var loader = new THREE.PLYLoader(); loader.addEventListener('load', function (event) { var geometry = event.content; ...

Using jQuery, generate a dynamic form to create a multidimensional array

I've set up a form where additional dropdowns can be dynamically added if the user clicks on a specific link. Here's an example of how it looks: <div class="dynamic-sale"> <select name="sizes[]" id="sizes" class="entry-dropdown"&g ...

Is there a way to pause and await the completion of an axios post request within a different axios interceptor?

Here are my axios interceptors: instance.interceptors.request.use( (config) => { const accessToken = localStorage.getItem("access_token"); const auth = jwt_decode(accessToken); const expireTime = auth.exp * 1000; co ...

Observer for Genetic Mutations or Node Insertion in the Document Object

In my Adobe Captivate script, I have set up automation on the first slide to create courses. The script generates UX, navigation elements, intro/end motions, a game, and inserts spritesheets with characters. Previously, I used DOMNodeInserted to monitor m ...