Using JavaScript or TypeScript to locate the key and add the value to an array

My dilemma involves an object structured as follows:

[{
   Date: 01/11/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '5' },
   {Title: 'Comment', Ans: 'Awesome' }
   ]
},
{
   Date: 01/11/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '2' },
   {Title: 'Comment', Ans: 'Bad' }
   ]
},
{
   Date: 09/12/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '3' },
   {Title: 'Comment', Ans: 'Okay' }
   ]
}]

My goal is to structure a new object in the following way:

[{
   Date: 01/11/2022
   Ratings: ['5', '2']
},
{
   Date: 09/12/2022
   Ratings: ['3']
}]

I am attempting to filter this data by date and extract all the ratings for each specific date.

Answer №1

To start, utilize the Array#reduce method on the array in order to generate a dictionary object that groups elements based on their Date. Then, apply the Array#map function to recreate an array of objects.

const group = (arr) => 
   Object.entries(arr.reduce((acc, { Questionnaire, Date }) => {
      const [{ Ans }] = Questionnaire;
      (acc[Date] || (acc[Date] = [])).push(Ans);
      return acc;
   }, {})).map(([date, rating]) => ({ Date: date, Ratings: rating }));
   
const res = group([{Date:'01/11/2022',Questionnaire:[{Title:'Rating',Ans:'5'},{Title:'Comment',Ans:'Awesome'}]},{Date:'01/11/2022',Questionnaire:[{Title:'Rating',Ans:'2'},{Title:'Comment',Ans:'Bad'}]},{Date:'09/12/2022',Questionnaire:[{Title:'Rating',Ans:'3'},{Title:'Comment',Ans:'Okay'}]}]);

console.log(res);

Answer №2

If you're struggling with these issues, one option is to explore the lodash library, which offers a variety of helpful functions without requiring additional dependencies.

   Date: 01/11/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '5' },
   {Title: 'Comment', Ans: 'Awesome' }
   ]
},
{
   Date: 01/11/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '2' },
   {Title: 'Comment', Ans: 'Bad' }
   ]
},
{
   Date: 09/12/2022,
   Questionnaire: [
   {Title: 'Rating', Ans: '3' },
   {Title: 'Comment', Ans: 'Okay' }
   ]
}]

const output = _.chain(data)
        .groupBy('Date')
    .map((v,k) => ( {Date: v[0].Date, Ratings: v.map(o => o.Questionnaire.find(q => q.Title === 'Rating')).map(v2 => v2.Ans)}))
    .value()
console.log(output)

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

A guide on verifying if two arrays of integers are permutations using JavaScript

Is there a way to determine if two sets of integers in JavaScript are permutations? For example, given the arrays: a = [1, 2, 3, 4, 5] and b = [2, 3, 5, 1, 4] I want a function that will return true if they are permutations of each other. ...

Convert string to integer value

Is it possible to convert a literal string type (not runtime value) to its corresponding numerical type, for example '1' to 1? I am looking to restrict a variable to only being a key of an object (assuming the type of obj is precise since TypeSc ...

Limitations of MaterialUI Slider

Looking for a solution to distribute 350 points across 8 sliders, each with a range of 0-100 and 5 marks at 0, 25, 50, 75, and 100. With each step consuming or returning 25 points, the challenge lies in allowing users to adjust the points allocation withou ...

Utilizing a TypeScript function to trigger an action from within a Chart.js option callback

Currently, I am utilizing a wrapper for Chart.js that enables an animation callback to signify when the chart has finished drawing. The chart options in my code are set up like this: public chartOptions: any = { animation: { duration: 2000, ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Unable to use addEventListener on media queries exceeding 768px

When testing the site on Firefox 49 and Chrome 63, I encountered the same issue. Clicking on each card worked fine on iPhone4, Galaxy 5, and iPhone 8 using Chrome. However, after switching orientations from 640px to 320px portrait view, the top card would ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

Revitalize access token with Keycloak in Javascript

I am currently working with keycloak-js version 8.0.1 and have a function called getToken that checks if the token is expired. If it is expired, the function refreshes it; otherwise, it returns the current token. The issue I am facing is that even though t ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Arranging items by specific criteria in ng-repeat for a personalized sorting experience

Within my controller, I have an object named $scope.addresscards. The JavaScript code is provided below: var myApp = angular.module('myApp', []); function MyCtrl($scope) { $scope.addresscards = { "work_address": { "location":"w ...

Using Regular Expressions in Express routing

Does anyone have experience serving a file with a dynamic hash in its name on a specific route? The file is named like workbox-someHash.js and the hash changes every time the app is deployed. I attempted to serve it using the following code snippets: &qu ...

Save only the most recent iteration of the javascript file in the cache

I've encountered an issue with browser caching of JavaScript files, even though I've utilized FileETag MTime Size in my htaccess file to verify the modified time and size for detecting the latest version. My current method of including JavaScri ...

Could we confirm if this straightforward string is considered valid JSON data?

There are numerous intricate questions on Stack Overflow about whether a complex structure is considered valid JSON. However, what about something much simpler? "12345" Would the provided code snippet be considered valid JSON? ...

Node-pty in NWjs application causing DLL malfunction

When attempting to run a terminal emulator / command prompt in NW.js using xterm JS and node-pty, I encountered a DLL Error. The following is the log: Uncaught Error: A DLL Initialization Routine Failed. \\?\C:\Users\volke.a\ ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Is it possible to utilize JavaScript for displaying a continuous stream of images?

In this scenario, you are tasked with working with an image API and need to send a POST request to retrieve an image stream for display on the rest of your webpage. While I am able to use jQuery to make an ajax request to the service upon page load, I am ...

Guide to uploading a PDF to Google Drive and embedding it on an HTML static website

I manage a static HTML site for a small food shop. They require monthly menu uploads in PDF format. I believe uploading to Google Drive would be a more efficient solution than creating a separate admin view for file uploads. Can anyone advise me on how to ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...