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

Optimal Timing for Loading Initial State from Database Using Vuex

In my Vue/Vuex project, I have a simple setup where I retrieve a list of categories from my database using an HTTP GET request. Before implementing Vuex, I used to fetch this data directly in my main component when it was created. Now with Vuex, I have g ...

Decoding deeply nested JSON arrays in Swift

Having trouble figuring out how to parse JSON using Swift. The goal is to extract the RouteKey and routeNAME from this XML content. I've experimented with various tutorials and attempted to utilize quicktype, but nothing seems to be working. { "respo ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Using a Python variable to add a column to a MySQL table after receiving an API response

After receiving an API response, I am struggling to insert the product_id Python variable into my MySQL table. The variable is formatted as prod_ABc123 when returned from the response. Despite trying various solutions found online, such as ALTER TABLE and ...

Retrieving information from React elements

Recently, I ventured into the world of React and started building a mock website for online food ordering. One of my components is called Items, which utilizes props to display all the food items on the webpage. import { useState } from "react"; ...

Exploring the process of setting up Jasmine tests for both services and controllers in Angular.js

I have been facing challenges in creating accurate tests for my Angular services and controllers, even though they are functioning correctly. I have searched extensively for a solution to this problem. Below is an example of my controller: angular.module ...

The Angular binding for loading does not correctly reflect changes in the HTML

Whenever a user clicks the save button, I want to display a loading indicator. The state changes correctly when the button is clicked, but for some reason, reverting back the value of the loading property on scope to false doesn't update the UI. Coul ...

What is the best way to swap out an icon based on the chosen option?

Here is my code: $('#mySelect').on('change', function() { var value = $(this).val(); $(".title").html(value); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href=" ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Issue with accessing Contacts API functionality in Firefox OS application

I have followed all the instructions provided in this documentation, but I keep encountering errors. My testing environment is the "Firefox OS 2.2" simulator. In my manifest file, I have included two permissions as follows: "permissions": { "deskto ...

What is the best way to incorporate a gratitude note into a Modal Form while ensuring it is responsive?

Currently, I have successfully created a pop-up form, but there are two issues that need fixing. The form is not responsive. After filling/submission, the form redirects to a separate landing page for another fill out. Expected Outcome: Ideally, I would ...

Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology ...

What is the process for verifying and authenticating a token's header?

Trying to incorporate token in the search functionality. The token is used to check the header for identification, ensuring that the request passes through all steps. If incorrect, the request is cancelled and returned. Requested JSON { "header": { "To ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

Error message: Object literal is limited to declaring existing properties

The source code was obtained from this Codesandbox demo: CodeSandbox - Cover Image Example Subsequently, an .eslintrc configuration file was generated with the following content (the only content present): { "extends": "react-app" } However, a TypeScri ...

How to Unravel a JSON Document Using Pandas

I've been attempting to convert a JSON file into a pandas DataFrame. Despite trying various solutions like pd.json_normalize(data.json), none have proven successful. It seems that the file is more intricate and contains nested JSON data. How can I fl ...

Utilizing API pointers in JSON PHP programming

Currently, I am diving into the world of JSON and PHP through APIs. The issue I am facing involves extracting data from Array 0. The output can be viewed at the bottom by following the link. I have searched extensively for solutions online, but I am still ...

What are some ways to disguise websockets?

I'm currently working on writing a JavaScript client that sends websockets to a node.js/ws server. I've been doing a lot of research and have come across information indicating it's useful, or even required by RFC, to mask all data sent from ...

The HTML Bootstrap collapse feature is not functioning correctly upon the initial button press

Could you assist me with implementing a bootstrap and javascript collapse feature? I have two collapsible cards. The first card should be visible initially, but then switch to the second card when clicked on a link. However, upon the first click, both card ...

How can I tally the frequency of characters in a given string using Javascript and output them as numerical values?

I am in the process of tallying the frequency of each individual character within a given string and representing them as numbers. For example, let's consider the string "HelloWorld". HELLOWORLD There is one H - so 1 should be displayed with H remov ...