Switching columns to rows using JavaScript

I came across a solution on Stack Overflow about swapping rows with columns in a matrix using JavaScript. However, it didn't work for me (probably because I'm still learning).

The data is structured in arrays like:

id [1, 2, 3]
caption [one, two, three]
title [One, Two, Three]

My goal is to convert these arrays into rows:

arr= [1, one, One]

Unfortunately, when trying the following code snippet:

var res = [];

for(i in this.fields) {

    for(j in this.fields[i].value) {

        res[j][i] = this.fields[i].value[j];

    }

}

I encounter an error "TypeError: can't convert undefined to object."

In PHP, a similar method works fine, but I need assistance in achieving this functionality in JavaScript. Thank you in advance.

UPDATE for simplification:

var arr = [];
arr[0] = [];

arr[6][0] = 5;
/*
Exception: can't convert undefined to object
@Scratchpad/1:4
 */

Typically, we iterate through strings using indexes like 0-0, 0-1, 0-2 until the end of a row before moving to the next row. But in my case, I require iterating through columns first - 0-0, 1-0, 2-0 before moving to the end of a column and then repeating the pattern.

UPDATE regarding "this". By adding a couple of lines:

console.log(this.fields[i].value[j]);
console.log('indexes: i='+i, 'j='+j);

You'll notice that there are no undefined values present.

4
indexes: i=0 j=0
1
indexes: i=1 j=0
1
indexes: i=2 j=0
one
indexes: i=3 j=0
One
indexes: i=4 j=0

Answer №1

Your source code seems to contain a few errors that need addressing. It's crucial for your this.fields value to be properly structured in order for the code snippet to function correctly. Here is an example of how it should look:

this.fields = [
    { values: [10, 20, 30] },
    { values: [40, 50, 60] },
    { values: [70, 80, 90] }
]

If your this.fields variable matches this structure, then you're on the right track towards solving the issue at hand. The error message you mentioned,

TypeError: can't convert undefined to object
, suggests that your variable may not be formatted as described.

In order to make sure your code works seamlessly, we need to ensure that res recognizes that its second dimension consists of arrays by explicitly defining it. Adding if(i === 0) res[j] = []; will address this problem.

With the corrected data structure and our suggested fix in place, your code snippet should operate smoothly:

var res = [];

for(i in this.fields) {
    
    for(j in this.fields[i].values) {

        if(i === 0) res[j] = [];
        res[j][i] = this.fields[i].values[j];

    }

}

Answer №2

There is a clear mistake present in the loop structure here. When iterating through the elements, the code attempts to access res[j][i] without first checking if res[j] has been defined, leading to an error. To rectify this issue, you can add a conditional statement to ensure the element exists before assigning a value:

var res = [];

for(i in this.fields) {

    for(j in this.fields[i].value) {

        if( !res[j] ) { 
            res[j] = []; 
        }

        res[j][i] = this.fields[i].value[j];

    }

}

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

Utilize Laravel to trigger a route action based on a dropdown selection change, generating a unique URL

In my code, I have a dropdown select containing the list of the next 12 months: <select name="month" id="specificMonth"> @foreach(Carbon\CarbonPeriod::create(now()->startOfMonth(), '1 month', now()->addMon ...

Patience is key when letting AJAX calls complete their execution in jQuery functions

In each of my 3 functions, I have a synchronous AJAX call. Here is an example: function() { a(); b(); c(); } a() { ajaxGet(globals.servicePath + '/Demo.svc/GetDemoList/' + sessionStorage.SessionId,function(data, success) {}, '&apos ...

What is the best way to create a mirror effect on one div by clicking another div?

I have created a schedule grid and I am looking for a way to allow users to click on the UK hour and then have the corresponding U.S time highlighted. Is there a CSS solution for this? The functionality I need is to be able to select multiple hours. I have ...

Displaying file when JQuery dialog is opened

I am utilizing a JQuery dialog to load a partial view within it. $("#WOdialog").dialog({ width: 765, resizable: false, closeOnEscape: true, modal: true, clos ...

Divide a nested list into individual lists

I am working on a navigation menu with nested lists and I need to split the nested lists using jQuery while keeping the original headings intact. Can anyone help me achieve this? Below is the HTML code: <ul id="bigList"> <li><a href="#"& ...

How to make a unique array of arrays in Javascript without any repeated elements

Hello fellow programmers! I'm diving into Javascript and facing a little challenge that I need help with. Let me share some data that I'm dealing with: <pre> [ [ { "id": 2759178563, "title": "Ergonomic Paper Computer", ...

Interact with HTML style attribute using JavaScript

Is there a way to retrieve a specific CSS property from the style attribute of an HTML element, without considering the stylesheet or computed properties? For example: <div style="float:right"></div> function fetchStyleValue(element, propert ...

I'm unable to locate my test text on the main page of my React web application

At the moment, my React application is running on port 3000 using npm start. I have made the decision to incorporate MySQL into the web app by executing yarn add express mysql. In order for this to work, I have configured server.js to listen on port 3001 ...

Picture not appearing on the webpage due to a connection issue with the sqlite database

I am working on creating a user profile feature where users can upload their profile picture. The uploaded picture is saved in local storage within a specific directory, and the URL of this image is then stored in the database linked to the connected user. ...

What is the best way to insert a row into a JavaScript table while incorporating a cell that utilizes the datepicker function in jQuery?

Currently, I am working on a javascript function: function addItem(tableID){ var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var el ...

Nested arrays in the JavaScript programming language

Is this JavaScript code accurate: var options = []; options.push(["Tom","Smith"]); options.push(["Mary","Jones"]); where each item in options is a two-element array of strings. I plan to add items to options using a for loop. Furthermore, can I i ...

Experiencing delays when loading more than 200 input fields on the screen due to

So I've been working on a project that involves having potentially unlimited input fields. However, once I add around 200 items, the performance starts to degrade significantly. You can see a demo of this issue here: (To test: Focus on the last input ...

Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property? items() { return this.table.filter.keyword ? this.dataArray.filter( item => item.nombre.toLowerCase().includes(t ...

I am interested in utilizing Maven and paulhammant (Selenium_java) to input text into a textefield

When attempting to write in the text field using selenium, I encountered an error stating "unexpected identifier". Any assistance with this issue would be appreciated. See image for more details ...

Create a definition for the keys type of an object based on an array

I am looking for a way to dynamically assign symbols from an array called TYPES_ARR as keys in the variable TYPES_GENERATED. I want each key in TYPES_GENERATED to have a corresponding symbol value. const TYPES_ARR = [ 'HttpClient', 'Par ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...

The use of jquery UI.js is causing issues with loading select menus dynamically

When attempting to load a dynamically loaded select menu on my page using Ajax/PHP, I encountered an issue where the jquery UI plugin prevented the data from loading. As a result, I was unable to see anything when changing the first select menu. Below is ...

Minimize API Requests in Your AngularJS Application

Currently in the process of developing a straightforward web application that interacts with an API service. One issue I've encountered is the API call limit, which hinders the functionality if exceeded. How can I optimize my API calls to stay within ...

Make jQuery fire an event when the "enter" key is pressed

I'm trying to create an event that will trigger when the "enter" key is pressed. I've been using this code, but for some reason it's not working and I can't figure out why. After searching everywhere, I came across this snippet that see ...

Show the chosen item from a dropdown menu using Bootstrap

Here is the HTML code that I am working with: <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="h ...