Issue
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
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);
Answered By - kind user
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.