Converting HTML Matrix to JSON using Typescript for API transmission

I have created a unique Matrix visual with additional features, but I am currently facing difficulties in extracting the data into JSON format and sending it through an API. Below is the HTML code for the matrix (which resembles a table structure). I would appreciate any suggestions on how to convert this Matrix HTML into JSON format. Could you please provide more detailed explanations? Thank you very much for your assistance!

// Here is the Matrix that needs to be converted into JSON

           Northeast   Southern
California 5            6
Florida    10           15

// The HTML structure is as follows:

<div class="datagrid">
    <table>
        <tbody>
            <tr>
                <th></th>
                <th colspan="undefined">Northeast</th>
                <th colspan="undefined">Southern</th>
            </tr>
            <tr>
                <th>California</th>
                <td>5</td>
                <td>6</td>
            </tr>
            <tr>
                <th>Florida</th>
                <td>10</td>
                <td>15</td>
            </tr>
        </tbody>
    </table>
</div>

// The expected JSON format should look like this:
[
    {
        "name_column_field": "Northeast",
        "value": 5,
        "name_row_field": "California"
    },
    {
        "name_column_field": "Northeast",
        "value": 10,
        "name_row_field": "Florida"
    },
    {
        "name_column_field": "Southern",
        "value": 6,
        "name_row_field": "California"
    },
    {
        "name_column_field": "Southern",
        "value": 15,
        "name_row_field": "Florida"
    }
]

Answer №1

To simplify this problem, I find it helpful to start by organizing the data into a nested array structure to represent our matrix.

const trs = document.getElementsByTagName("tr")

const matrix = []
// using a nested for loop to populate our matrix
for (let i = 0; i < trs.length; i++){
    matrix.push([])
    for (let j = 0; j < trs[i].children.length; j++){
        matrix[i].push(trs[i].children[j].textContent)
    }
}

// console.log(matrix) to visualize the nested arrays

const obj = []
// utilizing nested loops to iterate through the matrix and construct our object
// starting at index 1 as our labels are at index 0
for (let i = 1; i < trs.length; i++){
    for (let j = 1; j < trs[i].children.length; j++){
        obj.push({
            name_column_field: matrix[0][j],
            value: matrix[i][j],
            name_row_field: matrix[i][0]
        })
    }
}

// converting the object to JSON format
const completedJson = JSON.stringify(obj)

If you prefer to achieve this in a single for loop, here is an alternate approach:

const trs = document.getElementsByTagName("tr")

const obj= []
for (let i = 1; i < trs.length; i++){
    for (let j = 1; j < trs[i].children.length; j++){
        obj.push({
            name_column_field: trs[0].children[j].textContent,
            value: trs[i].children[j].textContent,
            name_row_field: trs[i].children[0].textContent
        })
    }
}

const completedJson = JSON.stringify(obj)

console.log(completedJson)

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

How can one encode an array of hashes using Jbuilder?

Can someone help me figure out how to encode this JSON object using Jbuilder? "should" : [ { "term" : { "tag" : "wow" } }, { "term" : { "tag" : "elasticsearch" } } ] ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Transmitting a JSON Array Using Python

I am working on an MVC Web Api and successfully adding new records using a "simple REST Client" with the following request: URL: http://localhost:4585/api/users Headers: Content-Type: application/json; charset=utf-8 Data: [{ "username": "name1", "email": ...

Incorporate a New Feature into my NPM Package

I've been searching high and low for an answer to this, but I'm still stuck. I'm working on a module in Angular 2 with ng-module, and everything is functioning properly. However, I'm struggling to assign a property to another property w ...

Tips for extracting specific input values from a JSON object

My goal is to analyze a user-input text field and count the occurrences of capital and lowercase letters in the alphabet, as well as other characters. At this stage, I have successfully generated JSON output containing the results. However, my next objecti ...

The issue of 'window is undefined' arises when utilizing window as a useValue provider in Angular 4 with

When compiling an Angular 4.0.2 application ahead-of-time, and defining a provider using useValue import { OpaqueToken, Provider } from '@angular/core'; export const windowToken = new OpaqueToken('window'); export const windowProvider ...

Javascript - Issue with Ajax causing additional commas in JSON responses

I'm attempting to send a request to a RESTful server using the HTTP module in Node.js. Due to the large response size (64 chunks, approximately 100kb), the HTTP module combines the chunks into a single string response like this: res.setEncoding(& ...

I'm running into an issue with deserialization and getting an error from Newtonsoft.Json.JsonConvert. Can anyone

public List<CoinMarket> GetCoinMarket() { List<CoinMarket> coinMarket = new List<CoinMarket>(); var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get"; try { using (var Client = new System.Net.Http.H ...

Is there a way to retrieve JSON output from an express-openapi mysql.query() function?

I am stuck trying to convert the results of a MySQL Query into JSON format using a REST API. In my attempts, I have tried to return the users variable and also applied a JSON.parse(JSON.stringify(users)); function. The console.log(users) shows a valid JS ...

Guide: Creating two distinct objects in a single HTTP request using a JSON file

Developed a database using Java Spring and Hibernate involving a responsible entity and an account entity linked with a OneToOne relationship. Below is the code snippet: REST controller : @RestController @RequestMapping("/test") public class test { ...

Replacing `any` in TypeScript when combining interfaces

Currently using Express and attempting to explicitly define res.locals. Issue arises as in the @types/express package, Express.Response.locals is declared as any, preventing me from successfully overwriting it: types/express/index.d.ts: declare namespace ...

Tips for addressing style issues within innerText

I am trying to use PrismJS to highlight HTML code, but the inner text function doesn't recognize line breaks (\n). <pre class="language-markup background-code"><code [innerText]="getHtmlCode()""></code> I have been working wi ...

`Firebase User Instance and Custom Firestore Document`

Recently, I posted a question regarding Google Firebase Angular Firestore switchMap and encountered some issues. The question can be found here. After exploring AngularFireAuth, I learned that it is used to create a User object with fixed values, requirin ...

Saving an image from a URL directly to the assets folder: A step-by-step

I'm currently working on my first Android app using Ionic and Cordova. I need to fetch an image from a REST API and save it on the device so that it can be accessed offline. Here are the versions I am using: Ionic: Ionic CLI : 6 ...

TypeScript erroneously defines data type

Here is a snippet of code that I am working with: interface Ev<K extends keyof WindowEventMap> { readonly name: K; readonly once?: boolean; readonly callback: (ev: WindowEventMap[K]) => void; } function createEventListener<K extends keyo ...

Using TypeScript for React with Mapbox GL

Hey there, I'm a newcomer to React and Typescript. I decided to dive into Typescript instead of raw JS, but now I'm facing an issue with adding layers to a react-map-gl element. Error: Type '{ id: string; type: string; paint: { 'sky-typ ...

Encountering an error message that reads "State.Push is not a valid function" upon integrating

Currently, I am working on developing a Todo app using react-typescript and redux. During testing, I noticed that the app functions properly without redux-persist, displaying the list of added tasks. However, upon integrating redux-persist, the store does ...

Developing a Fresh Entry on Monday.com Using Python

Is there a way to use Python to add a new item on Monday specifically on a Monday? I am working with a board that has multiple columns which need to be filled. How can I select a particular column and input a value into it? def ADD_data(api_key:str) -> ...

Encountering the error "Element implicitly has an 'any' type because expression of type 'string' cannot be used to index type '{}'" can be frustrating when working with React TypeScript

I'm encountering an issue when trying to access an object with an id in the code below. An error message stating 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type ' ...

Error: Material UI encountered a problem with type error - number 0 cannot be iterated (property Symbol(Symbol.iterator) cannot be read)

I am currently working with the MUI(Material UI) App bar. You can find it here. The version I am using is v6.1.1. In the sandbox environment, everything seems to work fine when testing. However, when implementing it into my project, I encounter the follo ...