Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma.

The task at hand is to extract unique results from a table in order to display them in a filter on the front-end.

Let me give you an overview of my table structure. It's called People, and it holds various details about individuals like their name, country, preferred language, profile type, department, etc.

My goal is to perform a database query that fetches distinct values from specific fields.

Currently, I am achieving this with the following query:

const contentFromDatabase = await this.prisma.people.groupBy({
     by: ['profileType', 'preferredLanguage', 'department'],
});

This query returns an array similar to the one shown below:

[
    {
        "profileType": "professor",
        "preferredLanguage": "en",
        "department": "Automotive"
    },
    ...
]

However, what I aim for is a structured output as follows:

{
    "profileType": [
        "business", "professor", "student"
    ],
    "preferredLanguage": [
        "en", "fr"
    ],
    "department": [
        "Automotive", "Books", "Garden", and more...
    ]
}

Since accomplishing this solely through database queries seems impractical, I attempted to create a custom function but faced difficulties.

Key Points to Consider:

  • I currently use single arrays but might transition to associative arrays in the future.
  • In the example above, I group by 3 fields, but this may expand dynamically based on requirements.
  • The purpose of this function is to populate filters with existing data within the database, catering to client preferences.

Your insights and assistance are greatly appreciated!

Answer №1

I experimented with this idea, you could create a function that encapsulates the following logic, where inp represents the array obtained from prisma.

let inp = [
    {
        "profileType": "professor",
        "preferredLanguage": "en",
        "department": "Automotive"
    },
    ...
];

/**
 * Function to generate the initial container object
 * with properties corresponding to the input array elements
 * @returns the newly created object
 */
const createInitialObj = () => {
  const obj = {};
  Object.keys(inp[0]).forEach(key => {
    // using Set to handle duplicate items
    obj[key] = new Set();
  });
  return obj;
}

// Extract properties from input array and populate the initial object accordingly.
inp = inp.reduce((acc, item) => {
  for (const props in item) {
    acc[props].add(item[props])
  }
  return acc;
}, createInitialObj());

// Convert sets to arrays
for (const props in inp) {
  inp[props] = Array.from(inp[props]);
}

console.log(inp);

This approach is adaptable for dynamic properties.

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 steps should I follow to update this React Navigation v5 code to v6?

As I delve into my studies on React Native, I came across the deprecation of the tabBarOptions feature. I understand that now we need to include it in screenOptions, but I'm facing issues with implementing this in my code. I tried enclosing them in br ...

Explore the wonders of Jest and Playwright by heading over to youtube.com and discovering an exciting video!

As part of my job responsibilities, I have been tasked with automating tests for a web application that our team developed. Using Playwright and Jest, I am required to write automation scripts from scratch. To practice utilizing Playwright, I decided to cr ...

Triggering jQuery events can be customized by excluding certain elements using the

Is there a way to hide the div "popu" when clicking on the img "tri"? I've tried using .not() since the img is a child of the div popu, but it didn't work. Also, I need to make sure that clicking on the div "textb" does not trigger the hide actio ...

The component "SafeAreaViewRN" could not be located within the UIManager

Upon attempting to open a bundle on my Android device, I encountered the following error message: A warning was displayed stating that the app was accessing a hidden field in android's view accessibility delegate. Additionally, an Invariant Violati ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

I have implemented a bootstrap modal, but whenever I trigger a function on the JavaScript side, it automatically closes. I am aiming for the modal to remain open

<div id="responsive-modal3" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none; " data-keyboard="false" data-backdrop="static" ng-init = "populateBidSpocData()" > <div cl ...

What part of the system generates sessions and cookies?

Is the following statement accurate? When developing a website, I utilize frontend javascript to create cookies and backend languages such as php or ruby to manage sessions? If this is correct, does the creation of sessions involve the browser generating ...

Encountering an issue with undefined property 'path' while attempting to upload an image on the frontend in React

I have encountered an issue while trying to upload an image on the frontend. The error message displayed is: message: "Cannot read property 'path' of undefined" status: "fail" When I log req.file on the backend and attempt to ...

Discover the exact location of an HTML element within an iframe

I am currently attempting to determine the position of an element that is within an iframe. I have written the following code for this purpose: // Custom function to calculate the position of an element on the page function getElementPosition(elem){ var ...

In Internet Explorer 8, experiment with creating a unique event in plain JavaScript and then capturing it using jQuery

Currently, I am facing an issue with IE8 regarding the execution order of scripts. There is a piece of code that needs to run before JQuery is loaded so I can fire a custom event. This event will be detected later by another section of code once JQuery ha ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates: SELECT id, ( 3959 * acos( cos( rad ...

Tips for retrieving the value of a table cell when the checkbox in the corresponding row is selected

Within my project, I am utilizing a table. The html code I am using is as follows: <table id="assTB" border="1px" cellspacing="0"> <colgroup> <col style="width:15%"> <col style="width:15%"> <col sty ...

Issue with JSON data not functioning properly in AJAX request

I have been facing an issue with detecting whether a database entry has been successfully input. I am sending the new inserted ID and a JSON variable to an AJAX call, which works fine in all browsers but not in phonegAP. Despite that, the data is being suc ...

Is there an issue with the JavaScript functionality of the max/min button?

Help needed with maximize/minimize button functionality as my JavaScript code is not working. Any suggestions for a solution would be greatly appreciated. Thank you in advance. Below is the code snippet: <html> <head> <script> $(functio ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

Issue detected with XMLHttpRequest - "The requested resource does not have the 'Access-Control-Allow-Origin' header."

Currently, I am working on the frontend development of an application using Angular 2. My focus is on loading an image from a third-party site via XMLHttpRequest. The code I have implemented for this task is as follows: loadFile(fileUrl) { const ...

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

What is the best way to generate a complete PDF of a webpage using pdfmake?

I'm currently developing a web application and facing the task of converting an HTML page, which contains multiple tables and datatables, to a PDF format. To achieve this, I've chosen to utilize the library pdfmake. Below is the script that I ha ...