Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javscript/TypeScript: Find the key and append value as an array

I have an object which is like

[{
   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' }
   ]
}]

I’m trying to create a new object which looks like

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

I’m trying to filter it by date and get all the ratings for that particular date

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could firstly Array#reduce the array to create a dictionary object to group elements by Date, thenArray#map over it to recreate the 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading