Converting array data into an HTML table using Javascript

I have a two-dimensional array containing strings, structured like this:

[["Application1", "11106.exampleserver.com", "11109.exampleserver.com", "11102.exampleserver.com", "11105.exampleserver.com" "Database, AFPUOR(KNAJKLD)", "Database, UOQZRNJ(LKUJD)" ],
 ["Application2", "44407.exampleserver.com", "11106.exampleserver.com", "11104.exampleserver.com", "Database, POJPR (OIUOLWA) ", "Database, UIAHSD (JJJQEP)" ],...]

And so on.. Each time with a different number of servers and databases.

I am looking for the best way to sort the applications by database/server and display or save this information. How should I manage this array?

To achieve this, I require an HTML table: The table header should display the application name followed by the respective servers and databases (separated).

Currently, I can extract the Databases using this code:

for(j=0; j < columns.length; j++){
    for(i=0;i < columns[j].length; i++){
        var db = columns[j][i].match("Database")
        if (db != null){
            console.log("APP: " +  j + ": " + columns[j][0] + " , ID: " + i + ": " + db.input)
            //outputs for example: APP: 0: Application1, ID: 5: Database XYZ
        }
    }
}

And for extracting Servers, I use the following code:

for(j=0; j < columns.length; j++){
    for(i=1;i < columns[j].length; i++){
        var db = columns[j][i].match("Database")
        if (db == null){
            console.log("APP: " +  j + ": " + columns[j][0] + " , ID: " + i + ": " + columns[j][i])
            //outputs for example: APP: 0: Application1, ID: 1: Server1.1
        }
    }
}

Answer №1

Take a look at this solution where I have organized the data by application and then by type:

var d = [["Application1", "11106.exampleserver.com", "11109.exampleserver.com", "11102.exampleserver.com", "11105.exampleserver.com", "Database, AFPUOR(KNAJKLD)", "Database, UOQZRNJ(LKUJD)"], ["Application2", "44407.exampleserver.com", "11106.exampleserver.com", "11104.exampleserver.com", "Database, POJPR (OIUOLWA) ", "Database, UIAHSD (JJJQEP)"]];

var data = {};

for (var i = 0; i < d.length; i++) {
    data[d[i][0]] = {
        Server: [],
        Database: []
    };
    console.log(d[i][0]);
    for (var j = 1; i < d[i].length; j++) {
        console.log(d[i][j]);
        if (typeof d[i][j] == 'undefined')
            break;

        if (d[i][j].match('Database')) {
            data[d[i][0]]['Database'].push(d[i][j]);
        } else {
            data[d[i][0]]['Server'].push(d[i][j]);
        }
    }
}

document.write(JSON.stringify(data));

Here is the resulting output:

{
    "Application1": {
        "Server": [
            "11106.exampleserver.com", 
            "11109.exampleserver.com", 
            "11102.exampleserver.com", 
            "11105.exampleserver.com"
        ], 
        "Database": [
            "Database, AFPUOR(KNAJKLD)", 
            "Database, UOQZRNJ(LKUJD)"
        ]
    }, 
    "Application2": {
        "Server": [
            "44407.exampleserver.com", 
            "11106.exampleserver.com", 
            "11104.exampleserver.com"
        ], 
        "Database": [
            "Database, POJPR (OIUOLWA) ", 
            "Database, UIAHSD (JJJQEP)"
        ]
    }
}

Answer №2

Give this a shot,

in your HTML

<table>
        <thead>
            <tr>
                <th>App</th>
                <th>ID</th>
                <th>DB</th>
                <th>Server</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

in your JavaScript

const table = document.getElementsByTagName('tbody')[0];

data.forEach((entity,index) => {

    let rowData = {}

    rowData.appName = entity[0]
    rowData.id = index
    rowData.databases = []
    rowData.servers = []

    entity.forEach(value => {    
        if (value.match('DB')){
            rowData.databases.push(value)        
        }else{
            rowData.servers.push(value)   
        }

    })

    appendRow(rowData)
})


function appendRow(rowData) {

    table.innerHTML +=  `<tr>
        <td>${rowData.appName}</td>
        <td>${rowData.id}</td>
        <td>${rowData.databases.join(',')}</td>
        <td>${rowData.servers.join(',')}</td>    
    </tr>`

}

Trust this guides you!

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

What is the best way to initialize React-map-gl with the user's current location as the default latitude and longitude?

Is there a way to render the map with default values of viewport set to user's location without needing to click a locate me button? <ReactMapGL mapboxApiAccessToken={mapboxApiKey} mapStyle="mapbox://styles/mapbox/streets-v11" ...

Utilizing Numpy Arrays for Graph Representation

The data is currently in a specific format: tail head P01106 Q09472 P01106 Q13309 P62136 Q13616 P11831 P18146 P13569 P20823 P20823 P01100 ... Are there any suggestions for converting this data into a graph using a numpy array? I am interested in ca ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Express functions properly when handling the root route, but encounters issues with sub routes as it sends empty response bodies

Inside the routes.ts file: const router:Router = express.Router() // Route to get all blogs router.get('/',async (req:Request,res:Response)=>{ res.status(200).send("message sent") }) router.get('/admin',async (req:Requ ...

Issue with Braintree Integration - custom form failing to generate nonce

When I followed the code in the documentation, the nonce did not appear at the server side and I couldn't find any hidden input field for the nonce being submitted. I was only able to make it work with the drop-in form and could see the nonce on the ...

What is the best way to display three unique maps simultaneously on separate views?

In this scenario, I have incorporated three separate divs and my goal is to integrate three maps into them. The javascript function that controls this process is as follows: function initialize() { var map_canvas1 = document.getElementById('map_canva ...

The windows phone application is experiencing an issue where the output is not displaying properly when using Json and

Although there are no errors in the code, the application is not displaying any output. I am attempting to retrieve data from php, MySql in a Json response. The application only shows the loading bar without loading any data. Please assist me. {"Hotel":[{ ...

Seeking a way to display a random div at a 1% rate without generating additional div elements

Searching for an answer to display only one div with a rate of 1/100. Currently, I am utilizing the following JavaScript: var random = Math.floor(Math.random() * $('.item').length); $('.item').hide().eq(random).show(); This method wor ...

What is the process for appending a value to an array of JSON objects?

I have a JSON array containing objects which I need to pass the values to the DataTables. [{ _id: '58a2b5941a9dfe3537aad540', Country: 'India', State: 'Andhra Pradesh', District: 'Guntur', Division: ...

What is the best way to use the copy files npm module to recursively copy all images from a source folder to a destination folder?

Is there a way to use the copy files command to transfer images (.png, .jpg) from an "src" folder to a "dist" folder while retaining the same filepaths internally and also ensuring it works recursively? https://www.npmjs.com/package/copyfiles I am curren ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Associating information with a dropdown menu

My goal is to bind a drop-down using a global variable (the array name). The binding works correctly here: Click here - dropdown is populating fine var name = ['us', 'china', 'kenya', 'us', 'china', &ap ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

How come the function is being triggered by my onclick button as soon as the page loads?

Currently, I am experiencing a challenge in my NodeJS project with Express. The issue lies with my EJS client side file when it comes to handling button click events. In my EJS file, I have imported a function from a JS file and can invoke it using <% ...

Direct a flow to an unknown destination

What I am trying to achieve is writing a stream of data to nowhere without interrupting it. The following code snippet writes the data to a file, which maintains the connection while the stream is active. request .get(href) .on('response', func ...

Is there a way to identify the specific list item that a draggable element has been dropped onto within a jQuery sortable with connected draggable lists?

Take a look at these two sets of items: user's inventory <ul id='list1'> <li>Apple</li> <li>Banana</li> </ul>available products <ul id='list2'> <li>Orange</li> ...

Is there a way for me to prevent the setTimeout function from executing?

I have a function that checks the status of a JSON file every 8 seconds using setTimeout. Once the status changes to 'success', I want to stop calling the function. Can someone please help me figure out how to do this? I think it involves clearTi ...

Are there any advantages to using arrays with non-contiguous indices that outweigh their drawbacks?

When working with JavaScript arrays, it's important to note that arrays can have gaps in their indices, which should not be confused with elements that are simply undefined: var a = new Array(1), i; a.push(1, undefined); for (i = 0; i < a.length; ...

Is there a way to ensure that a statement will not execute until the completion of a preceding function?

I am encountering an issue where the window.open function is being called too quickly, causing my other function not to finish and post in time within my onclick event. I attempted to address this by setting a timeout on the trackData() function, but it o ...

What is the best way to update a specific value in an object without affecting the rest of

Below is a data object: { name: "Catherine Myer", age: 23, birthday: "august" } If I want to pass this data as a prop to a component, but also change the age to 24, how can I do that? <NextPage data={author.age = 24}/> The ...