Converting the table outputs into div elements

I recently sought help with JavaScript on this platform. I needed a script to parse a CSV file and display it as HTML.

Fortunately, someone provided me with a lot of assistance. However, the issue is that the output is in the form of a single row table. The rows in the CSV file do not have a fixed number of columns or data, resulting in varying lengths for each row.

I have been attempting to use if statements to specifically extract data such as 'Last name' or 'known for' in order to organize the results.

What would be the most effective approach for this? I plan to style the output data so I believe using div IDs would be more suitable than tables. Additionally, where should I make modifications in the code (bearing in mind my limited knowledge in JavaScript)?

The if statement I tried (probably incorrect):

function firstName($container){
  var firstN = $container;
  var n = firstN.includes("First Name");

  if (n != 0){
    document.getElementById("first_name").innerHTML="First name = ";
    return;
  }
}

Main block of code (CSV file can be accessed at ):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery-1.12.3.min.js" type="text/javascript">
</script>
<title>Untitled Document</title>
<script type="text/javascript">
// Some JavaScript functions here...
</script>
<style type="text/css">
body {
  font-family: arial, helvetica, sans-serif;
  font-weight: normal;
  font-size: 13px;
  color: #000;
  text-align: left;
  margin: 3px 0px;
}

#wrap {
  padding: 20px;
}

#wrap table {
  border: solid 1px;
  border-collapse: collapse;
  background-color: aliceblue;
  height:400px;
  width:100%;
}

#first_name {
    height:200px;
    width:200px;
    background-color:#0C0;
}

</style>
</head>

<body>

<button onclick="myFunction()">Click me</button>
<div id="wrap"></div>

<div id="first_name">
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</body>
</html>

Thank you for your help!

Answer №1

In a nutshell, this is just another version of the common question on how to convert JSON into an HTML table that has been asked many times on SO. I will guide you through the process while also pointing you towards existing solutions.

CSV (comma-separated values) data typically appears as:

Col1,Col2,Col3,Col4
row1value1,row1value2,row1value3
row2value1,row2value2
row3value1,,row3value3,row3value4

Although not always the case, you can view CSV as a concise way of representing tabular data in text format, with rows and empty cells denoted by ",,". If we were to visualize the above CSV as a table in Excel, it would look like:

Col1       Col2       Col3       Col4
row1value1 row1value2 row1value3
row2value1 row2value2
row3value1            row3value3 row3value4

Your current data consists of JSON "objects", each presented as a line. In JSON, an object is enclosed within { } and comprises key-value pairs. Each object resembles:

{"key1":"value1", "key2":"value2"}

JSON allows grouping objects into arrays using square brackets, [ ].

Translating the table into JSON gives us:

[{'Col1':'row1value1','Col2':'row1value2','Col3':'row1value3'},
 {'Col1':'row1value1','Col2':'row1value2'},
 {'Col1':'row1value1','Col3':'row3value3','Col4':'row3value4'}]

When dealing with JSON, you can iterate over each object in an array and retrieve specific values based on keys. This flexibility means the order of key-value pairs doesn't matter, and missing values are optional. Assuming knowledge of all potential keys (e.g., Col1, Col2, Col3, and Col4), you can:

"Loop through the array, place each object in a <tr>, and for each object, insert the corresponding values into separate <td> elements."

This is precisely what you aim to achieve, and various tools can assist you in this process. To get started, ensure your file begins with a [, ends lines (except the last) with a comma, and closes with a ]. If handling static data, a simple find/replace operation in a text editor can add necessary commas. For dynamically generated data, a more complex approach involving segmentation and concatenation may be required before using a JSON-to-HTML conversion tool. If stuck, consider posting a new query for guidance on converting JSON objects into an array.

Below are some recommended JSON-to-HTML-table resources for further exploration:

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

Is there a way to create a distinct page in NextJS for every individual FaunaDB Document?

I'm trying to figure out how to dynamically generate a unique title for each page within a specific sub-directory in my project. The code I've written doesn't throw any errors, but the Title component is rendering every title-item on every p ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

Utilizing Ajax Requests to Access Services in Zend Framework 2

After my previous inquiry about How to access a variable in my Service, I am now facing challenges accessing the Service from my View Helper through an Ajax Request. I have included a new method in the BookmarkAdvertService() to add a Bookmark. publi ...

Experiencing issues with Mvc Ajax form when trying to upload a file and encountering an

When using MVC Ajax.BeginForm for file upload, an error is encountered in Chrome: VM454:1 Uncaught SyntaxError: Unexpected token u. Here is the code snippet: PartialView Info.cshtml @using (Ajax.BeginForm("ChangeInfo", "Users", new AjaxOptions ...

When the screen is minimized, my website doesn't align to the center as expected

When the screen is maximized everything looks great, but when I minimize it, the content doesn't center. I tried using margin: auto; in the "main-div" class, but then everything shifted to the top left corner. So, I added a "wrapper-div" to contain th ...

Is there a way to make the sidepanel appear and be edited with just one click on a Chrome extension, instead of the current two-click requirement?

Currently, I am in the process of developing a Chrome dictionary game extension. In the initial phase of the project, the user should have the ability to right-click on a word, triggering the display of a side panel containing definitions sourced from a lo ...

Position several elements in alignment within Bootstrap columns on a single row

Looking for a way to align multiple items horizontally across two columns within a row in Bootstrap? Check out the sample HTML code below: <div class="container"> <div class="row"> <div class="col-sm-6"> <h1>Short Hea ...

What is the best way for Selenium in C# to identify and locate a specific span element by its value

I've been experimenting with different locators, but I'm struggling to find a straightforward solution for identifying the dynamic number within this span using C# Selenium. Initially, my focus is just on locating the span itself. <span inven ...

The default choice vanishes once a non-empty option is chosen

Here is a simple example illustrating my issue: JSFiddle. Initially, I have an empty/default option, but when I select something else from the drop-down, this default option disappears. How can I keep this default option visible after making a selection? ...

How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => { return Object.entries(obj).reduce((acc, [key, value]) => { return value ? { ...acc, [key]: value } : acc; }, {}) as T; }; During a database migration process, I encounte ...

Guide to decompressing HTML pages on the client side

I implemented a proxy code from an interesting article that I turned into an HttpHandler public void ProcessRequest(HttpContext context) { string url = context.Request["url"]; string contentType = context.Request["type"]; // no bu ...

Using PHP to interact with Xbox API

Recently, I have been utilizing xapi.us to fetch my XBL clips through their API. By using the code snippet below, I was able to display the result on my webpage... <?php $uxid = rawurlencode("PROFILE ID"); $ch = curl_init(); curl_setopt($ch, CURLOPT_U ...

Error: Failed to cast value to ObjectId in the author field of the Blog model withRouter ID "6359f421fd4678e2eba3ffee"

One of the models in my blog application is the blog model: let blogSchema = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, title: { type: String, required: true, unique: true }, description: { type: String, ...

Having difficulty adjusting the width of the CSS menu bar to fit the entire page

I found a useful CSS menu tutorial online that seems to work well, but unfortunately, it doesn't stretch the full width of the page. You can check out the tutorial here: Even after trying to set the width to 100%, the menu still falls short of extend ...

Utilizing ES6 modules in an Adobe XD extension: A comprehensive guide

Is it possible to utilize ES6 imports within XD plugins? When attempting to use import Vue from 'vue', the build task is successful, but XD throws an error in the developer console during plugin loading: Plugin Error: Error loading plugin <s ...

Angular firing a function in the then clause before the initial function is executed

I have a situation where I need to make multiple service calls simultaneously, but there is one call that must be completed before the others are triggered. I have set it up so that the other calls should only happen after the .then(function() {}) block of ...

Using Jquery to alter elements during every iteration loop

With the help of jquery, my goal is to iterate through all elements that belong to the "item" class and give them different background colors based on their index position. The array mapcolor contains a variety of colors (with a length matching the number ...

Utilize jQuery to target the parent element based on the href attribute and dynamically insert content

Here is the current snippet of HTML code I am working with: <div> <a href="http://example.com">example.com</a> </div> I am looking to insert a new div as the last element in this structure. This is my desired outcome: <div ...

Learn the process of invoking an Angular scope function from within a JavaScript function located within a controller

In my Angular controller, I have a JavaScript function where I am trying to call an Angular function. However, I am encountering the error: $scope.Name is not a function, $scope.dates is not a function. function validation() { $scope.page ...

Choosing an element in JQuery based on the value of its style property

I have three divs with the same class but different styles. I need to select only the third one using JQuery. <div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-draggable" tabindex="-1" role="dialog" aria-labelledby="ui-dialog-title-div ...