Is there a way to transform a dynamically created JavaScript table into JSON or XML format and then store it as a file?

A dynamic table of properties is created in JavaScript using a function:

// update table
PropertyWindow.prototype._update = function (text) {

  if (text === void 0) { text = "<no properties to display>"; }
  this._propertyWindow.html(text);

};
PropertyWindow.prototype._onModelStructureReady = function () {

  this._assemblyTreeReadyOccurred = true;
  this._update();

};
// create row for property table
PropertyWindow.prototype._createRow = function (key, property, classStr) {

  if (classStr === void 0) { classStr = ""; }
  var tableRow = document.createElement("tr");
  tableRow.id = "propertyTableRow_" + key + "_" + property;
  if (classStr.length > 0) {
    tableRow.classList.add(classStr);
  }
  var keyDiv = document.createElement("td");
  keyDiv.id = "propertyDiv_" + key;
  keyDiv.innerHTML = key;
  var propertyDiv = document.createElement("td");
  propertyDiv.id = "propertyDiv_" + property;
  propertyDiv.innerHTML = property;
  tableRow.appendChild(keyDiv);
  tableRow.appendChild(propertyDiv);

  return tableRow;
};

I am looking to convert the generated table into JSON/XML and save it into a new file. How can I achieve this?

https://i.sstatic.net/SKq1y.png

Answer №1

To convert the generated table into JSON, you can iterate through it using the code snippet below:

var dataSet = [];
var $headers = $("th");
// Specify your table selector here
var $rows = $("tbody tr").each(function(index) {
  $cells = $(this).find("td");
  dataSet[index] = {};
  $cells.each(function(cellIndex) {
    dataSet[index][$($headers[cellIndex]).html()] = $(this).html();
  });    
});

// Store the data in an object and convert it to JSON format (jQuery can also handle this during Ajax requests)
var jsonData = {};
jsonData.dataSet = dataSet;
alert(JSON.stringify(jsonData));​

Check out this similar discussion

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

Enter key triggering input change event is unresponsive in Internet Explorer

$("#inputBoxWidth").change(function() { var curValue = $("#inputBoxWidth").val(); alert(curValue); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="inputBo ...

Utilizing Google Analytics 4 in a React TypeScript Environment

Currently, there are two options available: Universal Analytics and Google Analytics 4. The reasons why I lean towards using Google Analytics 4: Universal Analytics is set to be retired on July 1, 2023, so it makes sense to start fresh with Google Analyt ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

How can you send an error message from Flask and then process it in JavaScript following an AJAX request?

So I have successfully created a Python backend using Flask: @app.route('/test/') def test(): data = get_database_data(request.args.id) # Returns dict of data, or None if data is None: # What should be the next step here? re ...

Angular - service workers leading to unsuccessful uploads

When uploading files using Uppy (XHRUpload) in my Angular 6 app, the process is smooth on localhost with the service worker disabled. However, enabling the service worker results in successful uploads only for small files, while larger files fail to upload ...

Unlock a multitude of outcomes with Sequelize

Is there a way to retrieve multiple results from Sequelize and store them in an array? For example, I want to fetch all the values in the name field from the test table and display them in the console. This is what I tried: test.findAll().them(function(re ...

The front-end is responsible for removing the last item from an array

Having an issue with my React code. Here is my parent component: class RoomPrice extends React.Component { constructor(props){ super(props) this.state = { room: this.props.room, prices: [] }; this.handleDeletePrice = this.h ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

Having trouble connecting to my MongoDB container using Node.js

I am facing an issue while trying to connect my local mongoDB docker, named "some-mongo", to my NodeJS backend server running on the same computer. The problem arises when attempting to establish the connection using the "mongoose" module. To launch my mo ...

Clicking on a row in the Gridview should trigger the expansion or collapse of the Nested

My current issue involves a nested GridView setup like this: <asp:GridView ID="gvParent" runat="server" DataKeyNames="id"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:GridView ID="gv ...

When adding objects to the database using .NET EntityFramework, only unique items will be saved. Multiple identical objects cannot be

I am working on a project where I need to create multiple instances of an Exercise object based on a template. The template includes the exercise name and the number of sets. However, when saving these objects to the database, only some are saved instead o ...

Can you explain the concept of 'each' when using the looping method in jQuery?

I'm grappling with accessing data within a table row. The data could be within a <td> tag, as text in an input field, or as a checkbox in an input field, or even as a button. To illustrate, here's a snippet of a small table: <table bor ...

jQuery selector for attributes with values that are higher than a specific amount using the ">" symbol or lower than a certain value using the "<" symbol

I currently have several div elements with the following structure: <div class="roomnamecta" data-price="1189" data-adult="3">Room 1</div> <div class="roomnamecta" data-price="578" data-adult ...

When attempting to access Element.object3D in A-frame using TypeScript, an error stating "The 'object3D' property does not exist on the 'Element' type" is encountered

As a Japanese student, I ask for your understanding regarding my limited English proficiency. Currently, I am working on developing an a-frame library that utilizes anime.js in TypeScript to create animations. However, I encountered an issue when attemptin ...

Steps for setting up and shutting down the server during integration testing with Express and Supertest on NodeJS

One issue that continues to plague me is the "Address already in use::3000" error which pops up whenever I run my tests. This is what I currently have set up: package.json "scripts": { "test": "jest --watchAll --verbose --runInBand --maxWorkers=1" ...

I am encountering a horizontal scroll bar despite setting the width to 100%

I am just starting out as a beginner in web development. I decided to create a webpage to practice my HTML and CSS skills. However, when I set the width of all elements to 100%, I noticed that I am getting a horizontal scroll bar. I have tried troubleshoot ...

RTM is lacking dropdown navigation menus

In Visual Studio 2013 beta versions, there were dropdown menus at the top of the javascript editor that functioned similarly to those in c# and vb editing. Have these been removed from the RTM or final release, or are they available with a specific version ...

Transform the C# DateTime to LocalTime on the client side using JavaScript

Utilizing the Yahoo API on my server to retrieve currency information can be done through this link: Yahoo Currency API This API provides me with both a Date and a Time, which I'd like to combine into a single DateTime object. This will allow me to e ...

Handlebars does not support loading data into variables using Express

My NodeJS/Express application utilizes Handlebars for templates, and everything works smoothly except when attempting to display data retrieved from an Express API. The data is successfully fetched and can be viewed in the Chrome debugger. In the problem ...