What is the best way to convert rows into columns within an array of values?

Below is the structure of my data:

let information = [
    { 
    X:[
    {title: 'Example1', quantity: 25},
    {title: 'Example2', quantity: 35}
    ], 
    Y:[
    {title: 'Sample3', quantity: 45},
    {title: 'Sample4', quantity: 55}
    ] 
    },
    {
    X:[
    {title: 'Example1', quantity: 250},
    {title: 'Example2', quantity: 350}
    ], 
    Y:[
    {title: 'Sample3', quantity: 450},
    {title: 'Sample4', quantity: 550}
    ]}
  ]

This is how I want to reorganize my data: https://i.sstatic.net/PSHni.png

You can see the array structure in JSFiddle here: https://jsfiddle.net/rj5e38v9/3/

Answer №1

To generate a table, you can utilize array reduce method to create an object with keys A and B. Then, iterate through this object to populate the table.

var data = [{
    A: [{
        name: 'Test1',
        amount: 20
      },
      {
        name: 'Test2',
        amount: 30
      }
    ],
    B: [{
        name: 'Test3',
        amount: 40
      },
      {
        name: 'Test4',
        amount: 50
      }
    ]
  },
  {
    A: [{
        name: 'Test1',
        amount: 200
      },
      {
        name: 'Test2',
        amount: 300
      }
    ],
    B: [{
        name: 'Test3',
        amount: 400
      },
      {
        name: 'Test4',
        amount: 500
      }
    ]
  }
]

const val = data.reduce((acc, curr) => {
  for (let keys in curr) {
    if (!acc.hasOwnProperty(keys)) {
      acc[keys] = [];
    }
    acc[keys].push(...curr[keys])

  }
  return acc;
}, {});

let tableStr = ''
for (let keys in val) {
  tableStr += `<ul>
  <li class="headerList">${keys}</li>
  ${val[keys].map(elem=>{return '<li><span>'+elem.name+'<span class="valCol">'+elem.amount+'</span></li>'})}
  
 </ul>`
}


document.getElementById('dataDisplay').innerHTML = tableStr
li {
  list-style-type: none
}

.valCol {
  margin-left: 50px;
  color: green;
}

.headerList {
  font-style: bold;
  font-size: 50px;
}
<div id="dataDisplay">


</div>

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 server encountered an error: TypeError - It is not possible to convert undefined or null into an

Check out this Code import { getProviders, signIn as SignIntoProvider } from "next-auth/react" function handleSignIn({ providers }) { return ( <> {Object.values(providers).map((provider) => ( < ...

Prevent scrolling on browser resize event

I am working on a basic script that adds a fixed class to a specific div (.filter-target) when the user scrolls beyond a certain point on the page. However, I am wondering how I can prevent the scroll event from triggering if the user resizes their brows ...

Is it possible to assign values from a double array to corresponding elements in a string array?

I have a task to create a program that displays a number from a double array alongside its corresponding element from a string array. Here's what I currently have: double[] numbers = new double[3]; numbers[0] = 1.1; numbers[1] = 7.8; numbers[2] = 6.0 ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

Using jQuery to organize object properties based on the value of another property

Within my collection, I have an array of objects structured as shown below. [ {"rel_id": 1,"forward_flag": true,"asset_id":5,}, {"rel_id": 1,"forward_flag": true,"asset_id":8}, {"rel_id": 1,"forward_flag": false,"asset_id":3}, {"rel_id": 2,"forwar ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

When a div is clicked, the text inside the button changes. If another div is clicked, the previous text is reset

I am seeking a solution for changing the text of a button within three columns when a specific 'advice-card' div is clicked on. The text should change to 'Hide' for the clicked div, and the other buttons should switch back to 'Show ...

observable arrays in knockoutjs

To simplify the problem I'm facing, let's consider this example: var ViewModel = function() { this.self = this; self.test = ko.observableArray([]); self.test2 = ko.observableArray([]); self.test2.push('1'); self.test.push({ 'f ...

Ways to eliminate the design from a previously selected list item

I'm working on creating a calendar that displays 3 booking times when a user clicks on a specific day. However, I am facing an issue where the styling (green color) remains on the selected day even if the user chooses a different day. Any assistance o ...

Questions regarding prototype-based programming in Javascript

I am interested in achieving the following using Javascript: function A(){ this.B = function() { ... }; this.C = function() { <<I need to call B() here>> } ; }; I came across a method of method overloading, but I am curious to know ...

Steps for updating inputs using a modal selection

I am currently utilizing the Laravel Framework and facing an issue where I need to allow users to choose a specific event to edit if they have multiple event records. I have already implemented a modal that displays all the events, but I am unsure how to c ...

mention the element to display on the pagination

I find the logic here quite puzzling. This particular code block seems to be related to pagination, as it involves a function that is triggered upon clicking. componentDidUpdate() { const { location } = this.context; const { query } = this; if ...

What is the best way to retrieve the value from local storage?

const value = document.getElementById("demo").getAttribute('value'); if(typeof(Storage)!=="undefined") { alert(value); localStorage.setItem("GetData", value); alert(localStorage.getItem("GetData")); } function loading() { alert("coming" ...

Mouseover feature for image is functioning, but having issues with alignment

I am currently working on displaying images upon mouse over actions. While the functionality is working perfectly, I am facing an issue where the displayed images appear below and the last image takes up space at the bottom. To rectify this problem, I woul ...

Connecting Peers in Windows Store App using HTML/JS

I am curious to find out if anyone has successfully created a peer-to-peer app for the Windows Store using HTML5 and JavaScript. I want client A of the app to be able to establish a connection with and send data to client B through either a TCP or UDP sock ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

A guide on inputting numbers into an array in C without the need to define the array size

Is there a way to read integers from standard input without knowing the number of values beforehand and store them in an array? Input Examples: 4 5 6 7 8 (or) 4,5,6,7,8 (or) 4 5 6 7 8 Output Example: Print the resulting array. In Python, this task can ...

Is there a way to display the description field instead of the Id in a table using pxp-ui?

I am currently working with a table in pxp-ui and have implemented the following column: subsystemId: { type: 'AutoComplete', isSearchable: true, label: 'Subsystem Id', ...

In PHP, validate if an array includes a portion of a specific value

I'm facing a challenge with 2 arrays: $array_x = array( array( "id" => 1, "merchant_reference" => "Ref 12345" ), array( "id" => 2, "merchant_reference" => ...

The hyperlink and criteria provided are accurate, however, the webpage remains stagnant

My login page is supposed to redirect to the contact confirmation page when I receive a 200 response from the server, but it's not working. Can you help me find my mistake? const [form, setForm] = useState({}); async function checkLogin() { tr ...