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

Do you know the proper method to refresh data on a UITableView?

Is this the correct approach to appending objects to my data source and then reloading the table? The datasource I am using is self.items //Creating a copy of current items self.itemsCopy = [self.items mutableCopy];//[[NSMutableArray alloc] initW ...

What sets Express.js apart from koa2.js in handling asynchronous functions?

I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code: router.get('/',(req,res)=>{ queries.getAll().then(stickers=>{ res.json(stickers) }) ...

Elegant method for politely asking individuals utilizing IE7 and earlier versions to leave?

TLDR: Politely ask IE6/7 users to switch browsers without accessing content. In essence, I don't want people using IE7/6 on my web app. I was considering using a doc.write function after loading to replace the page with a message stating "Sorry, your ...

Whenever I navigate to this specific route, I consistently encounter an error message in my console

VM28353:1 Error: Unexpected token 'o' found in JSON at position 1 at JSON.parse (<anonymous>) at getUser (auth.js?c7d4:11) at wrappedGetter (vuex.esm-browser.js?5502:335) at Object.eval [as getUser] (vuex.esm-browser.js?5502 ...

The selected value is not displayed in the Material UI select component

My select component is showing the menu items and allowing me to select them, but it's not displaying the selected value. However, its handle function is functioning correctly because when I choose an item, the value in the database gets updated. Bel ...

The issue of the window.open method malfunctioning on Internet Explorer 9

Struggling to make it work in IE9: Note: I forgot to mention that $variable is coming from a $_GET request based on a drop down menu selection. I am currently offline, <a href="#" onclick="window.open('https://domain.com/contact-form?chatq=& ...

Having trouble with Ajax and facebox integration issues?

My website utilizes ajax jquery and facebox for interactive features. You can check out a demo here. The div with the ID "#content" contains links to other pages that open successfully using facebox. However, when I reload the content of this div using aj ...

Strategies for smoothly navigating the page to a specific div every time

Currently, I am working on a form that requires submitting multiple child forms. To enhance user experience, I have incorporated jQuery functionality to display a message at the top of the page upon each submission. Now, my goal is to implement a feature w ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

Does JSON hijacking play a role with IE versions greater than 10 or Chrome versions greater than 30?

OWASP suggests wrapping json response with an object rather than returning a direct array. For instance: [{"id":5}] Is this vulnerability still relevant? Could it be exploited? After testing in Chrome, IE, and FF, I couldn't find a way to 'h ...

Modify the background color of a particular TD element when clicking a button using JavaScript and AJAX

When I click on the "Active account" button inside the designated td with the <tr id="tr_color" >, I want the value "1" to be added to the 'active_account' column in the database. I have been successful with this functionality. However, I a ...

Concealing and revealing content using JQuery based on user input in

I'm attempting to create a feature where the visibility of a password field is determined by the value of another input element. For instance, when the username is set to "admin", the password field should be hidden. If any other value is entered in ...

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...

Automatically forward to m.example.com on mobile devices using nodejs

Is there a way to create a subdomain in Node.js, such as m.example.com, and have it redirect to m.example.com on mobile devices? I've searched for answers but haven't found a satisfactory solution. One suggestion is to use nginx in front of Node, ...

Reviving jQuery Smooth Zoom Pan viewer following container resize

I am in the process of developing a responsive image viewer and have decided to incorporate the Smooth Zoom Pan plugin for enhanced pan/zoom functionality. Within my layout, I have two primary panels: the viewer container and a controls container that are ...

RobotFramework encounters difficulty locating an element using JavaScript

After working with RF for the past few weeks, I came across a persistent issue that has been bothering me. I keep getting the following error: The element with the locator 'XXX' (just a template) cannot be found. Upon investigating the span tha ...

Tips for converting an object into parameters for ng-include

What is the best way to create a serialized array of objects that can be used as parameters for ng-include in order to dynamically load data from the server? Using Angular controller and params with requests: app.controller("MyCtrl", function($scope) { ...

Having trouble adding a test card to the Google Pay testing environment and calculating the order total

How can I display the order total in GooglePay payment sheet? I could not find any documentation on this. Is it possible to do so? Even though I am using the TEST environment, I am unable to add any test card as mentioned in the URL provided below. Additio ...

Java: Custom Object References Stored in an Array

I am currently working on creating an array of custom object references. Below is a simplified version of the code I am using: import java.util.*; public class Map { private int[] dimension; private City[] cities; private int nCities; ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...