Converting an array of objects into a two-dimensional array

I am looking for a way to convert an array of objects into a 2D array (array of arrays). I have tried using map and Object.keys(), but I need to organize the values differently. Specifically, I want to push the first value of each object into the first array, the second value into the second array, and so on. Thank you in advance for your assistance.

The desired output

[
  ['2', '5', '8', '10', '12'],
  ['4', '10', '16', '20', '24'],
  ['6', '15', '24', '30', '36'],
  ['10', '25', '40', '50', '60']
]

The current output

[
  ['2', '4', '6', '10'],
  ['5', '10', '15', '25'],
  ['8', '16', '24', '40'],
  ['10', '20', '30', '50'],
  ['12', '24', '36', '60']
]

let obj = [
  {
    line1: '2',
    line2: '4',
    line3: '6',
    line4: '10'
  }, {
    line1: '5',
    line2: '10',
    line3: '15',
    line4: '25'
  }, {
    line1: '8',
    line2: '16',
    line3: '24',
    line4: '40'
  }, {
    line1: '10',
    line2: '20',
    line3: '30',
    line4: '50'
  }, {
    line1: '12',
    line2: '24',
    line3: '36',
    line4: '60'
  }
];

var output = obj.map(function(obj) {
  return Object.keys(obj).map(function(key) { 
    return obj[key];
  });
});

console.log(output);

Answer №1

To perform the transformation, you need to use indices and access the result set in reverse order.

var array = [{ line1: '2', line2: '4', line3: '6', line4: '10' }, { line1: '5', line2: '10', line3: '15', line4: '25' }, { line1: '8', line2: '16', line3: '24', line4: '40' }, { line1: '10', line2: '20', line3: '30', line4: '50' }, { line1: '12', line2: '24', line3: '36', line4: '60' }],
    result = array.reduce((r, o, i) => {
        Object.keys(o).forEach((k, j) => (r[j] = r[j] || [])[i] = o[k]);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

To ensure a consistent result, it is recommended to predefine the keys as an array.

var array = [{ line1: '2', line2: '4', line3: '6', line4: '10' }, { line1: '5', line2: '10', line3: '15', line4: '25' }, { line1: '8', line2: '16', line3: '24', line4: '40' }, { line1: '10', line2: '20', line3: '30', line4: '50' }, { line1: '12', line2: '24', line3: '36', line4: '60' }],
    keys = ['line1', 'line2', 'line3', 'line4'],
    result = array.reduce((r, o, i) => {
        keys.forEach((k, j) => (r[j] = r[j] || [])[i] = o[k]);
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Another method you can try is outlined below.

let data = [
  {
    line1: '2',
    line2: '4',
    line3: '6',
    line4: '10'
  }, {
    line1: '5',
    line2: '10',
    line3: '15',
    line4: '25'
  }, {
    line1: '8',
    line2: '16',
    line3: '24',
    line4: '40'
  }, {
    line1: '10',
    line2: '20',
    line3: '30',
    line4: '50'
  }, {
    line1: '12',
    line2: '24',
    line3: '36',
    line4: '60'
  }
];

var result = [];
for(var j = 0; j < data.length; j++){
   var position = 0;
   for(var info in data[j]){
      if(result[position] == undefined){
        result[position] = [];
      }
      result[position].push(data[j][info]);
      position++;
   }
}

console.log(result);

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

Implementing specific actions based on user selections in an Oracle APEX navigation bar

Within the application's navigation bar, there is a Home item that is present on all pages. I want to implement a feature where if the user clicks on the Home item, a warning message will pop up based on the page number, alerting them that any unsaved ...

Error encountered when attempting to initialize an array using a function in C

I'm trying to create an array of type set with all nodes set to NULL using calloc. However, I'm encountering an invalid initializer error in the main function. What could be causing this issue? struct set { int capacity; int size; cha ...

store the response from XMLHttpRequest in a JavaScript variable

This question has been asked twice before, but I still couldn't get it to work. After reading through the posts here and here, I learned about calling a callback function because the XMLHttpRequest is asynchronous (which seems obvious anyway). So, I ...

Troubleshooting: Unable to get the Bootstrap active navigation code to function

I've been struggling to make this code work in order to add the active class to my navigation list item, but it just won't cooperate. Home <li id="orange"> <a href="hotels.php"><span class="glyphicon glyphico ...

Enhancing a sophisticated algorithm

I find myself in a bit of a predicament here, as this may not be the most appropriate platform for such complex queries. However, I'm at a loss as to where else I can turn. I've been diligently working on a function for some time now, and while i ...

The autopostback feature of ASP.NET/Webform Textbox is not triggered when the onkeyup event contains a "setTimeout" function in Internet Explorer 9

I'm encountering a strange issue specifically on IE 9. The code works perfectly fine in Chrome and Firefox, but not in Internet Explorer. Below is the relevant code snippet: This problem is occurring in a legacy application built with VS2008. The "co ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

Show label and selection box

I've been trying to add a checkbox to the display tag table, but I'm having trouble getting it to function properly. I want the header checkbox to select all rows in the table when checked Additionally, individual rows should be selectable Whe ...

Angular JS: using data binding with dynamically inserted html elements

I'm currently experiencing difficulties with two-way data binding in AngularJS. I have provided a sample code snippet below: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular ...

I am encountering difficulties trying to create a draggable stacked bar chart using d3 v4. The main challenge lies in properly translating the svg elements during the dragging process

const dragFunction = d3.drag() .on("start", startDrag) .on("drag", duringDrag) .on("end", endDrag) function startDrag(d) { d3.event.sourceEvent.stopPropagation(); d3.event.sourceEvent.pre ...

What could be causing the misalignment of the Datepicker calendar in Material UI?

I have integrated a datepicker using the library "@mui/x-date-pickers/DatePicker". import { DatePicker } from "@mui/x-date-pickers/DatePicker"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { Locali ...

How can we ensure that the user's language preference is saved?

I'm currently working on implementing a language switcher feature for a website I've been developing. I'm facing an issue where the site doesn't remember the user's language preference and keeps reverting back to English. Any ass ...

Standardize all values for each key in sub-dictionaries and include them as additional key-value pairs

Suppose there is a dictionary containing nested sub-dictionaries: let dict = { "SEATTLE" : { "gross_sales" : 106766, "price" : 584.50, "dates" : [ { " ...

What is the best way to conceal specific series in a HighCharts legend?

In the chart, I currently have 4 series. At the moment, only 2 of them are visible while the other 2 are hidden when the chart first loads. As the user zooms in on the chart, the visibility of the series changes dynamically. I need help figuring out how ...

npm fails to install the dependencies listed in the package.json file

I've encountered an unusual issue. I'm attempting to install project dependencies on my server using a simple npm i command, but it's not generating a node_modules folder. I've already tried various suggested solutions such as running ...

Tips for setting up Reaction Roles in discord.js?

Having some trouble implementing this functionality, especially with my reaction role. Wondering if I am using the correct functions/methods. Any help would be greatly appreciated. New to discord bot development and might have a simple question, but any a ...

Modifying the value of an object key with Javascript

The information I am working with is structured as follows: obj = { pref: { language: 'English', } }; My goal is to update the language field to 'Spanish'. ...

When the function is called after rendering, the state within the class constructor is undefined

I am facing an issue that I can't seem to find any information on. I am passing the p1 props from my App component to the state of my Child1 component. However, when I attempt to access the state of s1 by calling the buttonHandler method, I encounter ...

The challenge of Nested Views in Angular UI Router

I'm struggling to understand the functionality of nested views in Angular UI Router. My configuration for $stateProvider is as follows: $stateProvider .state('login', { url: "/login", views: { 'main': { templateUr ...

Using an arrow function within an alert box that activates when clicking the 'onsubmit' button in a form

I have a code that currently outputs the function as is, but I want it to return the value of the 'p8' id using an arrow function. <form onsubmit="alert(()=>{document.getElementById('p8').value})"> <label>PA ...