Combining a 3D array into a 2D array with the addition of HTML tags around each value using JavaScript

3D array

// Array

var x = {
  "letter": [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ],
  "line": [
    { "data": [ 306, 830, 377, 651, 547, 369, 300, 148, 494 ] },
    { "data": [ 88, 339, 298, 87, 96, 108, 93, 182, 64 ] },
    { "data": [ 3157, 2943, 2724, 2116, 3700, 2980, 2449, 2494, 1057 ] },
    { "data": [ 2006, 1921, 2030, 615, 273, 415, 680, 286, 730 ] }
    ]
  };

Some variables

// Variables

var line = x.line;
var data = [];
for (var i = 0; i < line.length; i++) {
  data.push(line[i].data);
  }

The challenge at hand

// Problematic code (works only for fixed number of array objects, need a solution that can handle any number)

var listData = [];
for (var i = 0; i < line.length; i++) { listData.push(''); }
for (var i = 0; i < data[0].length; i++) {
  listData[0] += '<li>' + data[0][i] + '</li>';
  listData[1] += '<li>' + data[1][i] + '</li>';
  listData[2] += '<li>' + data[2][i] + '</li>';
  listData[3] += '<li>' + data[3][i] + '</li>';
  }

// Attempting another approach...

var listData = [];
for (var i = 0; i < line.length; i++) {
  listData.push('');
  listData[i] += '<li>' + data[i][/* ??? */] + '</li>';
  }

I aim to streamline the line[data] objects into one array, enclosing each value from the data objects in an html <li> tag, then merging them into a single string per object. Resultantly, listData should be structured as follows:

Desired outcome

listData == [
"<li>306</li><li>830</li><li>377</li><li>651</li><li>547</li><li>369</li><li>300</li><li>148</li><li>494</li>",
"<li>88</li><li>339</li><li>298</li><li>87</li><li>96</li><li>108</li><li>93</li><li>182</li><li>64</li>",
"<li>3157</li><li>2943</li><li>2724</li><li>2116</li><li>3700</li><li>2980</li><li>2449</li><li>2494</li><li>1057</li>",
"<li>2006</li><li>1921</li><li>2030</li><li>615</li><li>273</li><li>415</li><li>680</li><li>286</li><li>730</li>"
]

What I seek is a method that would function not just with 4 data objects, but with any original number of objects within x.

While I managed to achieve this with the existing 4 objects, I am struggling to implement it programmatically. Any assistance provided using my current variables would be highly appreciated! Many thanks.

Answer №1

To accomplish this task, utilize the map function. Begin by organizing the data into a multidimensional array, followed by creating a li element for each number:

var listData = x.line
  .map(function(obj){return obj.data})
  .map(function(ns){return '<li>'+ ns.join('</li><li>') +'</li>'})

This method is versatile and can handle any amount of data objects, each containing an array with varying numbers of items.

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

The error callback for Ajax is triggered even though the JSON response is valid

Within my JavaScript file, I am making the following call: $.ajax({ type: "POST", dataType: "application/json", url: "php/parseFunctions.php", data: {data:queryObj}, success: function(response) { ...

What is the best way to send HTML content from a controller using ajax?

Here is the code in my controller: public async Task<ActionResult> GetHtml(int id) { var myModel = await db.Models.FindAsync(id); return Json(new { jsonData = myModel.MyHtml }, JsonRequestBehavior.AllowGet); } This is ...

Having trouble sending HTTP requests in Angular 6

I am currently facing an issue in my Angular application while trying to send an HTTP POST request to a Spring RESTful API. Despite my attempts, I have not been able to succeed and I do not see any error response in the browser console. Below is a snippet ...

The dropdown menu is not appearing in the correct position when clicked

https://i.stack.imgur.com/fMyZQ.jpg Hello there, this link appears normal before clicking on it. But once clicked, it moves to the top of the page like so: https://i.stack.imgur.com/yZ0R0.jpg You can clearly see the difference. I have also provided the c ...

Dynamically attach rows to a table in Angular by triggering a TypeScript method with a button click

I need help creating a button that will add rows to a table dynamically when pressed. However, I am encountering an error when trying to call the function in TypeScript (save_row()). How can I successfully call the function in TypeScript and dynamically a ...

Can JavaScript executed within a web browser have the capability to manipulate files on the underlying host system's file system?

Is it possible to programmatically move files or folders from a website using code? I am aware that with Python and Node.js, this can be achieved through the OS, path, and fs modules. Can JavaScript running in a website also handle file management tasks ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Adjust a sub-document field using mongoose

My foundational structure var GameChampSchema = new Schema({ name: String, gameId: { type: String, unique: true }, status: Number, countPlayers: {type: Number, default: 0}, companies: [ { name: String, login: String, pass: ...

Error: The gulp-cssmin plugin encountered a TypeError because it attempted to read the property '0' of a null

I am attempting to condense my code, but I am encountering this error: D:\gulp-compiler\node_modules\gulp-cssmin\node_modules\clean-css\lib\selectors\extractor.js:66 return name.replace(/^\-\w+\-/, ...

Calculate the time difference between the stroke of midnight on a specific date and the present moment using JavaScript, node.js, and

Looking for a way to determine if the current moment is less than 3 minutes after midnight of the next date using a JavaScript Date object (e.g. 09.08.2020 15.45). This condition should evaluate to true for times ranging from 09.09.2020 00:00 up until 09.0 ...

Adjust the size of the <textarea> to match the height of the table cell

Below is the code I am using to generate a table containing an image along with a <textarea>: <table border="1" style="border-color: #a6a6a6" cellpadding="4" cellspacing="0" width="702">\ <col width="455"> <col width="230"> ...

How can we verify email addresses and URLs in PHP? Let's discuss converting this validation process

After studying the code extracted from the jquery.validate plugin, I find it quite challenging to decipher. My goal is to convert this code into PHP and I would greatly appreciate any assistance in understanding each segment of the regular expression codes ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Eliminating repetitions from a pair of strings separated by commas

Looking for an efficient way to compare two comma-separated strings and remove duplicates completely. The goal is to eliminate any duplicate items that exist in both strings. For instance, when comparing cat,dog,alligator with alligator,parakeet, the desi ...

Trouble with PUT request for updating user password using Express.js with mongoose

I've encountered a puzzling issue while working on my Express.js application. Specifically, I have created an endpoint for updating a user's password. Surprisingly, the endpoint functions flawlessly with a POST request, but fails to work when swi ...

The attempt to cast the value of "X_Value" to an ObjectId in the "X_Model" model at the path "_id" has failed due to being of type string

I'm facing an issue while attempting to update multiple records simultaneously using their IDs. The error message I encounter is puzzling, even ChatGPT couldn't provide a solution. Here's the error: Cast to ObjectId failed for value " ...

Having difficulty locating audio files within a Next.js project

I am facing challenges when trying to import my audio files into a redux slice. Currently, I am attempting to retrieve my audio files from the app > public > audio directory. I have made efforts to access my audio files through 2 different director ...

How to manipulate local JSON files using AngularJS

I recently started learning angularjs and have been spending hours online trying to figure out how to access data from a local json file without the need for hosting it on localhost. Unfortunately, I haven't come across any solutions yet. I attempted ...

What techniques can I use to streamline the following?

var cleanWord = word .split(/[^a-z0-9\s.\|]/gi) .join("") .replace(/([~@#$%^&*()_+=`{}\[\]\\:;<>\/ ])+/g, ""); I suspect that I am redundantly using the join function twice here. Is there a way to ...