Changing an array of objects into an object containing two arrays in TypeScript

I am dealing with an input array of objects

[
  { col1: 'col1value1', col2: 'col2value1', col3: col1value3},
  { col1: 'col1value2', col2: 'col2value2', col3: col1value2}
]

My goal is to transform this into two arrays structured as follows:

columns:["col1" , "col2","col3"],
data: ["col1value1","col2value1" , "col1value3"] ,
      ["col1value2","col2value2" , "col1value2"]

I am currently using a method involving nested foreach loops to achieve this. Is there a more efficient or faster approach?

Answer №1

One way to retrieve all the columns is by using the Object.keys() method, then you can iterate through the array and extract the values by utilizing the Array.prototype.map method along with Object.values().

const sampleData = [
  { col1: 'value1', col2: 'value2', col3: 'value3' },
  { col1: 'value4', col2: 'value5', col3: 'value6' },
];

const headers = Object.keys(sampleData[0]);
const tableData = sampleData.map((row) => Object.values(row));
console.log(headers);
console.log(tableData);

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

Troubleshooting browser cache issues when using webpack chunks and vue.js components

The Issue I am facing a frustrating challenge with cached Vue.js components. Strangely, I cannot replicate this issue on my own devices, but whenever we push client-side updates, users start complaining about broken interfaces. The only solution seems to ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

Using Node.js and React to dynamically render a different HTML file in response to a request

We are currently working on implementing AMP pages for our project. Our current solution involves detecting a query in the URL, such as: myurl.com?amp=1, and completely redrawing the page with the necessary markup. However, our server is set up to choose ...

What is the best method to sum two variables in jQuery when numerous rows are created dynamically?

I am currently working on a dynamic table that generates multiple rows, each containing a modal with a form. Each modal form has a unique ID assigned to it. My goal is to display the combined result of two variables in a disabled text field. Can anyone gui ...

Sending properties through the React Router to a specific component

Within my component, I have a material table that triggers a function when the edit button is clicked: //MaterialTable.js ... const handleEdit = (e, Data) => { console.log(Data) return(<EditFunction id={Data.id} />) ... The purpose of ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

"How to prevent users from using the back button on Google Chrome and Edge browsers

window.history.pushState(null, null, location.href); window.addEventListener('popstate', () => { history.go(1); alert('The use of back button is restricted.'); }); An issue has been identified where the code snippet above d ...

Issue with displaying Angular variable on webpage is not happening as expected

It's been a challenging journey trying to self-teach myself Angular.js. Unfortunately, I've hit a frustrating roadblock - the variables just won't display properly on the webpage! <!DOCTYPE html> <html ng-app> <head> & ...

Executing the GetDoc function multiple times in a React application

Utilizing Firebase for Authentication & Storage and incorporating useContext from react to encase my application with an authentication layer. After retrieving the user from the authentication layer, I proceed to fetch the user's details from Firesto ...

How can I ensure that TypeORM, Type GraphQL, Apollo Server, and Azure Functions work together seamlessly?

I have an Azure Function written in TypeScript that utilizes various technologies such as TypeORM, Apollo Server, and TypeGraphQL. The function involves creating resolvers for projects and tasks and establishing a database connection. import { createConne ...

Discovering the Solution: Angular 17's Answer to Troubleshooting Peer Dependency Conflicts

After upgrading Angular to version 17 using npm --force, my application was running smoothly in a local environment. However, when attempting to deploy it (via octopus deploy), the npm install process was automatically triggered by .Net, resulting in a lis ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

Ways to obtain HTML as plain text

Issue: Whenever I use the console.log(${ref.current}) method, it displays a text like [object HTMLTableElement] instead of the desired text <h1> bla bla bla</h1>. Objective: How can I retrieve the HTML value as a string in ...

Sending an HTML form to an external ASP script

I am currently attempting to create an HTML form that can submit multiple variables to an external ASP file that generates a chat window. The given example I am working with can be viewed through this link, although it involves a two-step process. In the ...

Using JavaScript to display content on the screen

As a newcomer to Javascript, I'm looking for a way to display my variable on the webpage without utilizing <span> or innerHTML. var pProductCode = $('[name=pProductCode]').val(); $('input[id*="_IP/PA_N_"]').each(function(i){ ...

Looking for assistance with implementing a jQuery function for an onClick event on

I've been diving into learning jquery and managed to create a basic checkbox feature with a function that allows you to set all options as read-only by checking the "None of the above" button. <html> <body> <form id="diagnos ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...

Specific Character Count in Regular Expressions

THIS IS DISTINCT FROM THE REFERENCED QUESTION because I have extensively researched and tested various solutions before resorting to posting this inquiry. I am in need of a validation for inputs that adhere to the following criteria: The first character ...

How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this: <div *ngIf="groupCheck; els ...

"Troubleshooting Node JS: Resolving the Issue of

I'm encountering an issue where connecting to localhost:3000 or 127.0.0.1:3000 results in a blank page. You can find the code on my GitHub repository here: https://github.com/InfamousGamez/halp Here is a screenshot of localhost:3000, showing what I ...