Transform a column containing objects into a row containing an array of objects

My data is organized in an object with column names such as name, age, and gender, each assigned values for those columns.

{
  'name': {
    0: 'Alpha',
    1: 'Beta',
    2: 'Gamma'
  },
  'age': {
    0: 21,
    1: 25,
    2: 30
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
}

I am looking to convert the above object into an array of objects.

Desired output :

[{
    name: 'Alpha',
    age: 21,
    gender: 'Male'
}, {
    name: 'Beta',
    age: 25,
    gender: 'Female'
}, {
    name: 'Gamma',
    age: 30,
    gender: 'Male'
}]

My approach so far ?

I attempted using Object.keys() to create an initial object with keys as {name: '', age: '', gender: ''}. Then, I tried to loop through the values of each key using Object.values() to bind the values dynamically against each key, but encountered difficulties in achieving this task.

const obj = {
  'name': {
    0: 'Alpha',
    1: 'Beta',
    2: 'Gamma'
  },
  'age': {
    0: 21,
    1: 25,
    2: 30
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
};

const columnNameObj = {}
const arr = []
Object.keys(obj).forEach(column => {
  Object.values(obj[column]).forEach((item, index) => {
    columnNameObj[column] = obj[column][index] // <-- Here I am doing a mistake as it iterates the whole loop and the last value get assigned to the object property. Object should be pushed on each iteration instead of ending the inner loop but somehow I am stuck here.
  })
  arr.push(columnNameObj);
})

console.log(arr);

Answer №1

If the nested values in your data are accessed using sequential integers as keys, you can leverage these keys to retrieve corresponding indexes from the result array within a nested loop. Utilize nullish coallescing assignment (??=) to set up each result object if it is not yet created.

const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };

const result = [];

for (const [key, values] of Object.entries(input)) {
  for (const [index, value] of Object.entries(values)) {
    (result[index] ??= {})[key] = value;
  }
}

console.log(result);

Alternatively, you can apply the same approach with a reduce() function along with a nested forEach() loop if that suits your preference.

const input = { name: { 0: 'Alpha', 1: 'Beta', 2: 'Gamma', }, age: { 0: 21, 1: 25, 2: 30, }, gender: { 0: 'Male', 1: 'Female', 2: 'Male', }, };

const result = Object.entries(input).reduce((acc, [key, values]) => {
  Object.entries(values).forEach(([index, value]) => {
    (acc[index] ??= {})[key] = value;
  });
  return acc;
}, []);

console.log(result);

Answer №2

If you want to transform data efficiently, consider using array reduce method

const information = {
  'name': {
    0: 'John',
    1: 'Jane',
    2: 'Michael'
  },
  'age': {
    0: 30,
    1: 28,
    2: 35
  },
  'gender': {
    0: 'Male',
    1: 'Female',
    2: 'Male'
  }
}
const keys = Object.keys(information);
const transformedData = Object.values(information).reduce((accumulator, current) => {
  let obj = {};
  // key will be 0, 1, 2 - this is used to get the value from the index
  for (let key in current) {
    obj[keys[key]] = current[key]
  }
  accumulator.push(obj)

  return accumulator;


}, []);
console.log(transformedData)

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

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

Unable to retrieve image data from Ajax to Java, but successful in receiving the image bytes

Currently, I am in the process of sending an image to the server side. The base64 formatted image is received from a third party and for bandwidth optimization reasons, I intend to send this data in binary form (decoding is essential). It is important that ...

How can I easily swap between the front and back cameras while using an app?

Trying to create a web-ar experience that allows users to switch between front and back cameras while utilizing SLAM/6dof with the back camera has been a challenging endeavor. While attempting this in PlayCanvas, I faced difficulties getting the front came ...

invoking a method of the grandparent from within the grandchild component

My components are nested three levels deep: <GrandParent /> <Parent /> <Child /> In the Child component, I have a button that, when double clicked, should call a function in the GrandParent component. <button @dblclick=&quo ...

Issues with CodeIgniter Calendar Preferences template functionality

Check out the $prefs. $prefs = array( 'month_type' => 'long', 'day_type' => 'short', 'show_next_prev' => true, 'next_prev_url' => ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

Displaying currency in Vue components

I'm having trouble maintaining the decimal format when trying to input currency values using numeraljs and plain javascript. I can't seem to find a solution to this issue. Below is my code snippet: <input v-model="amountValue">< ...

Is there a way to swap out memcpy() for strcat() in a function?

I've successfully implemented code that allows for inserting a substring into a specific section of an original string. However, I am curious about how to achieve the same result using strcat() instead of memcpy(). void insertString(char original[], ...

sending an object between JavaScript and PHP and vice versa

This task seems quite challenging and not easily achievable. Imagine having a button inside a div in HTML. When you click the button, you call a PHP function using AJAX. The goal is to send the element that triggered the click event (or any other element ...

What can be done to resolve the issue of 'this.state.*.map' not being a function

I am encountering an issue while trying to export a single row from my component import React, {Component} from 'react'; class TableRow extends Component { state = { row: [] }; componentWillMount() { this.setState({row: this.props.chil ...

The click-handler method in VueJS Paginate Component fails to activate

I'm currently working on a Vue Component code that involves pagination for a list. The pagination seems to be working fine, except for the issue I encounter when trying to navigate to the next page, which in this case is page 2. I've added a cons ...

Adding content to a paragraph using Jquery

I have 4 sets of data associated with a click-bind event. My goal is to retrieve the value from a hidden field in each set and display it in a paragraph elsewhere on the page when the corresponding checkbox is clicked. Currently, I'm focused on gettin ...

The issue of Json data being truncated when using ReadAsAsync and WriteToStreamAsync with the WebApi Formatter, while XML data operates without errors

Currently, I am faced with a strange issue while working on a project involving C#, WebAPI 2. The scenario is as follows: there is a service that calls a Controller and the content sent can be either in Json or XML format. The mechanism for making this ca ...

Utilizing JQuery Mobile AJAX to load JSON data

Hey there, I'm currently diving into the world of developing my first mobile app for my WordPress blog. One of the key components I've set up is the JSON API plugin on my WordPress site, allowing me to access my JSON Data via "example.com/api/get ...

Node.js failing to log chat messages

The goal is to log the chat message entered by the user in the console (terminal). Currently, there seems to be an issue with logging and I'm struggling to debug it. Keep in mind that I am a novice when it comes to NodeJS and only have basic knowledge ...

Issues with @material-ui/core and react-bootstrap imports are causing disruptions to the NextJS build process

After researching, I've come to realize that this issue is common among developers. Unfortunately, none of the solutions I found have worked for me. During npm run dev mode, everything in the project functions as expected, with all imports working se ...

json_encode: values indicating absence

<?php require_once (realpath(dirname(__FILE__) . '/../includes/database.php')); class User { public $email; public $password; public function find_email($email, $password) { global $database; $pswd = substr(md5($p ...

Prompting for confirmation when the "Close Button" is clicked in Bootstrap V5 Alert Dismissing

Looking to enhance the user experience by incorporating Sweetalert2 for a confirmation message within the Bootstrap version 5 alert component. Curious how it operates? Upon clicking the "Close Button" (X), the intention is to trigger a confirmation messa ...

Display a single value retrieved from an array returned by a MySQL database query using PHP

After running a PHP script that includes var_dump($row), the output is: array(1) { ["rmb4"]=> string(2) "10" } What method can I use to extract the value 10 from this? The data is retrieved from a SQL query. I am looking for an expression that will re ...

In React using Flow Type, the syntax [...mySet] doesn't function as expected, while Array.from(mySet) successfully converts the

Why is it that with React and Flow Type, the line of code displaying [{}] when using JSON.stringify([...mySet]) but shows the correct values with JSON.stringify(Array.from(mySet))? The issue seems perplexing as this behavior cannot b ...