Generate arrays with custom names by parsing JSON data

Currently, I am retrieving data from a MySQL database and converting it to JSON before passing it to a JavaScript class for chart display purposes. The challenge lies in creating arrays required by the chart from the JSON object without manually creating and populating them.

Here is what my object structure looks like:

var myJSON = [
        {"name1": "value11", "name2":"value21", "name3": "value31"},
        {"name1": "value12", "name2":"value22", "name3": "value32"},
        {"name1": "value13", "name2":"value23", "name3": "value33"}
]

I aim to transform it into this format:

var myData = {
"name1": ["value11", "value12", "value13"],
"name2": ["value21", "value22", "value23"],
"name3": ["value31", "value32", "value33"],
}

While I could manually create and populate the arrays, I believe there must be a more elegant solution. I have explored functions like Map, Object.keys, and Object.entries but haven't been able to crack the code.

My preference is to resolve this issue within JavaScript, but I've also included Mysql/PDO tags as alternative data fetching methods are on the table.

Despite my efforts since Friday, an elegant solution continues to elude me. Any assistance would be greatly valued.

Answer №1

I labeled the question with Mysql/PDO because I might be able to retrieve the information in a different way.

Absolutely, it is possible.

In order to obtain such an array, you will need to utilize FETCH_GROUP along with fetch_COLUMN

Answer №2

To implement this functionality, utilize the combination of reduce, forEach, and Object.entries:

var obj = [
  {"name1": "value11", "name2":"value21", "name3": "value31"},
  {"name1": "value12", "name2":"value22", "name3": "value32"},
  {"name1": "value13", "name2":"value23", "name3": "value33"}
]

console.log(obj.reduce((a, o) => (Object.entries(o).forEach(([k,v]) => a[k] ? a[k].push(v) : a[k] = [v]), a), {}))

reduce iterates through each object, maintaining previous values in a.

Object.entries generates key-value pairs for each object in the array.

forEach loops over each pair and appends the values to the accumulator a.

The one-liner broken down into separate lines:

var obj = [
  {"name1": "value11", "name2":"value21", "name3": "value31"},
  {"name1": "value12", "name2":"value22", "name3": "value32"},
  {"name1": "value13", "name2":"value23", "name3": "value33"}
]

console.log(
  obj.reduce((a, o) => (
    Object.entries(o).forEach(([k,v]) => 
      a[k] ? a[k].push(v) : a[k] = [v]
    ), a
  ), {})
)

Answer №3

Transform the data into an object by iterating through each key-value pair of the array item using Object.entries, ensuring an array is created at the key in the accumulator if needed, and then appending to that array:

var myData = [
  {"key1": "value11", "key2":"value21", "key3": "value31"},
  {"key1": "value12", "key2":"value22", "key3": "value32"},
  {"key1": "value13", "key2":"value23", "key3": "value33"}
];

const result = myData.reduce((accumulator, object) => {
  Object.entries(object).forEach(([key, value]) => {
    if (!accumulator[key]) {
      accumulator[key] = [];
    }
    accumulator[key].push(value);
  });
  return accumulator;
}, {});
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

I'm looking for a query that allows a user to select random rows from a database just once

I need a query that will select random rows from the database only once. In other words, if a user refreshes the page, the selected rows should remain the same. Currently, I am using the following SQL statement: SELECT * from table-name order by rand() li ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Error occurred during JSON parsing: String in the JSON object is not properly terminated

Can someone help me with this problem I'm facing? I am trying to fetch a JSON object from my Node.js backend that is the result of a MySQL operation. Here's the code snippet: app.get('/get_events/:playgroundId', cors(), function(req,r ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

Working with conditional rendering in React Native allows us to easily change text based on different conditions. By utilizing

Hello fellow React Native beginners! I'm currently working on a feature where the text output on the screen changes based on the time of day. Specifically, I want the screen to display 'Morning' if it's morning, 'Afternoon' i ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Exploring the process of incorporating a JavaScript library into an Angular project

I've encountered this issue before and know there are various workarounds available. I often search online for front-end design code to enhance the user experience of my projects, such as carousels, animations, and more. However, most of these project ...

What does the file_get_contents('php://input') contain when used with an HTML form submission?

I'm seeking clarification regarding the implementation of file_get_contents('php://input'). Specifically, I am interested in understanding what data is actually returned when this code is utilized within a submitted <form> for processi ...

What is the recommended ORM for implementing transactions in Node.js when working with MariaDB?

Seeking answers and solutions as I haven't had any luck finding them elsewhere. Possible choices include: Waterline (well-known but lacks transaction support) Sequelize (widely used but criticized for being bloated and complex to understand) node-o ...

Received an unexpected character '?' in NextJS

After setting up a fresh installation of Ubuntu 22.04.1 LTS and installing npm and docker, I encountered an issue while trying to start my NextJS web server with the command npm run dev. An error message appeared as follows: niklas@srv-code01:~/Desktop/Co ...

Utilizing D3's nested selection with JSON: Implementing .force() on nested elements

(After encountering unresolved issues from a previous question here, I am continuing the discussion by posting this follow-up question.) My data structure consists of nested JSON representing a tree, as shown below: [{ "name": "flare", "root": "tr ...

Angular 2: Emptying input field value on click event

I am experiencing an issue with resetting my input values. I have a search bar with filter functions. When I enter a value, it displays a list below and I want to add a function to these links. When I click on one of them, it takes me to another component ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

Modules failing to load in the System JS framework

Encountering a puzzling issue with System JS while experimenting with Angular 2. Initially, everything runs smoothly, but at random times, System JS struggles to locate modules... An error message pops up: GET http://localhost:9000/angular2/platform/bro ...

Adjust the CSS property of a div to have a fixed position when scrolling

I attempted to implement a fixed div on scroll in Vue.js using the following code: ... async created() { window.addEventListener('scroll', this.calendarScroll); } methods: { calendarScroll() { console.log('Scroll'); cons ...

Swap out a div identifier and reload the page without a full page refresh

I am interested in learning how to dynamically remove a div id upon button click and then add it back with another button click to load the associated CSS. The goal is for the page to refresh asynchronously to reflect these changes. So far, I have successf ...

13 Helpful Tips for Resolving Hydration Failure Due to Discrepancy in Custom Dropdown Display between Server and UI

Recently, I embarked on a project utilizing the latest version 13 of Next.js with its new app directory feature. As I integrated a custom dropdown into one of my pages, an error surfaced: "Hydration failed because the initial UI does not match what was ren ...

Bringing in a JSON file containing dictionaries of dictionaries with nested dictionaries into Pandas

I am currently extracting a JSON file from the RKI in Germany (equivalent to CDC). The data appears to be structured with dictionaries nested within dictionaries. My main focus is on the data dictionary nested within the "features" dictionary. However, eac ...

Mastering regular expressions in TypeScript

My goal is to perform linting on staged files that are either .ts or .tsx and located within the src folder. I am aware that for selecting all js files one can use "*.js": [--list of commands--] inside the lint staged property. I'm curious to learn m ...

Tips for efficiently storing a large JSON object in a session storage?

Currently, I am working on a project that involves saving rows retrieved from a database as JSON data to the user's session. This application utilizes jQuery on the client-side and is powered by the Spring MVC framework along with Hibernate on the bac ...