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

Time:11-10

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

CodePudding user response:

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);

CodePudding user response:

There are lots of ways without dependencies, but I'd suggest looking at the lodash library if you're finding these problems difficult.

   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)```
  • Related