Converting a dataset into an array of objects using Javascript or Typescript

I am working with an input object consisting of two arrays.

payload 

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

My goal is to convert these two arrays into objects as shown below: output = [];

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

I have been attempting to achieve this using reduce or other methods, but I am struggling. Currently, I am hard coding the index of columns in the data array. Is there a better and faster way to accomplish this without hard coding the column names?

This is how I am currently approaching it:

const indexofCol1= this.payload.columns.indexOf["col1"]

Then I use that index to map through the data array to retrieve all the values - which I know is not ideal.

Answer №1

To transform your data arrays into objects, you can utilize a combination of .map() along with Object.fromEntries(). Begin by applying the .map() function to your data arrays. Within each inner array (referred to as row), construct an object using Object.fromEntries(). This method requires an array consisting of [[key, value], ...] pairs. Create this array by mapping your cols array, where each key corresponds to a value in cols, and each value represents the respective item in your current row array.

Below is an illustration:

const cols = ["col1", "col2", "col3"];
const data = [["col1value1", "col2value1", "col1value3"], ["col1value2", "col2value2", "col1value2"]];

const res = data.map(row => Object.fromEntries(
  cols.map((key, i) => [key, row[i]])
));

console.log(res);
.as-console-wrapper { max-height: 100% !important;} /* ignore */ 

If your environment does not support Object.fromEntries(), a more compatible alternative involves employing Object.assign() along with the spread syntax:

const cols = ["col1", "col2", "col3"];
const data = [["col1value1", "col2value1", "col1value3"], ["col1value2", "col2value2", "col1value2"]];

const res = data.map(row => Object.assign({},
  ...cols.map((key, i) => ({[key]: row[i]}))
));

console.log(res);
.as-console-wrapper { max-height: 100% !important;} /* ignore */

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 process of transferring information from a JSON API to TypeScript models

When working with my JSON API in my services, I need to pass the data to my models. What is the most efficient way to accomplish this task? Currently, I am following this process: import { Attachment } from '.'; export class Contact { id: nu ...

The div element nested within the button is not visible

Fiddle I am trying to create a unique social button design that resembles the custom Google+ sign-in button: However, I encountered an issue where the second div element (to hold the right part of the button) is not displaying as expected: Here is the c ...

Sleek Carousel failing to display in Bootstrap5 Tab panel

When integrating the slick slider with Bootstrap5 Nav, I encountered an issue where the slider does not display within the active tab content unless the window is resized. Rearranging the sequence of embedded JavaScript did not solve the problem and actual ...

Creating a split button can be enhanced by incorporating a disabled button with a tooltip feature

I am attempting to create a split button using Material UI components such as ButtonGroup and Button. You can find more information about split buttons here. The issue I am facing is that the first button may need to be disabled and display a tooltip when ...

Sorting through items within a container object

I am currently working with an object named 'docs' that contains multiple objects within it. I am attempting to determine the count of entries that have specific values for both 'exopp_rooms_id_c' and 'is_active'. While this m ...

Confirmation Dialog with FancyBox for Deletion

Looking to add a delete confirmation dialog using FancyBox. The idea is to provide the url to FancyBox and then proceed to the defined url to perform the delete action when the user clicks on the "Yes/Confirm" button. Has anyone tried this before and hav ...

Tips for removing markers from personal Google Maps

I am having trouble deleting markers from my Google Maps using my code. The markers array seems to be empty even after adding markers. Can anyone help me troubleshoot this? Thank you! When I use console.log(markers.length) in the removeMarkers() function, ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Transfer a table row between tables - AngularJS

I am seeking guidance on how to implement ng-repeat in order to transfer data from one table to another. Essentially, I have a "master" table that displays data fetched from an API request. Each row in this table has a button labeled "favorite-this-row". W ...

Enhance Your ASP.NET Website with Dynamic Link Styles

Having some trouble with my main menu on my ASP.NET website. I'm looking to have the selected link change its color to black and stay that way until a different link is clicked. In simpler terms, I want the selected link to be highlighted. I've ...

Is it possible to utilize waxjs for retrieving data on NFTs within the Wax Cloud Wallet?

I am currently in the process of incorporating the Wax Cloud Wallet into my React/NextJS application. To achieve this, I am utilizing waxjs and referencing the documentation available here. At present, users can log into their accounts and the applicatio ...

Firefox compatibility issue caused by jQuery's appendTo function disrupting hyperlink functionality

I've successfully implemented the material design ripple effect using jQuery, which functions well in IE11 and Chrome 46. However, I've encountered an issue in Firefox 39 where applying the effect to links prevents redirection. Upon investigation ...

Tips for generating documentation using markdown within the docs directory on GitHub with the help of JavaScript

After browsing through numerous documentation websites, I have noticed that many of them share the same layout and features. This has led me to question whether there is a common library used by all these documentation sites. How do they achieve this unif ...

Using 'this' to access state in the Vuex Store

Currently delving into Vuex and studying this section of the official Vue documentation. I'm curious as to why one would access state with an argument instead of simply using this? I experimented with using this and found that it still worked. Vue Sa ...

Issue with Highcharts: Overlapping yAxis labels when displaying multiple series data

I am facing an issue with a highchart that I have rendered for multiple series data. The y-axis labels are overlapping. Is there a way to resolve this problem? You can view the chart here: https://jsfiddle.net/sharadkalya/mhg52js4/ https://i.sstatic.net/ ...

Why isn't the Angular directive resolving the dynamic button text variable?

Trying to implement an iPhone-style Toggle Button using CSS in Angular. The issue I am facing is that the dynamic button text variable "{{v1['btn2']}}" is not being evaluated properly the first time, although it works fine with static text. URL ...

provide the key and id to a node.js module

Currently, I am utilizing the Express framework to establish a module for handling requests to a third-party API. This particular API necessitates an ID and key to be transmitted. Rather than embedding these credentials directly into the module, I prefer ...

Triggering an event when selecting options in dropdown menus on Firefox

Currently, I am facing the following scenario: I have a single select box along with a tooltip that is displayed when the user clicks on the box to choose an option. The tooltip can easily be shown using CSS (select:focus ~ .tooltip) or jQuery by utilizin ...

Exploring the power of dynamic templates in Angular 4

After exploring numerous blog posts and discussions, I have yet to discover a solution for my template dilemma. The issue revolves around our straightforward icon component, where users can specify the desired icon and size directly in the template: impor ...

Understanding np.argmax() in Python: a comprehensive guide

The information provided for the np.argmax() function states that it will Return the indices of the maximum values along a specified axis. The given examples are clearly outlined: In[1]: x = np.arange(6).reshape(2,3) In[2]: x Out[2]: array([[0, 1, 2], ...