Recreate A Json Response Based On Existing Response
I have the json response with value week1,week2,week3,week4 in week key along with count based on category (meetingHash)and week wise.I tried to merge with .reduce but no luck I w
Solution 1:
You need to use map not reduce!
const data = [
{
"UserName": "Sarathy Devaraju",
"week": "Week 1",
"MeetingHash": "Hold/Uncategorized",
"monthinwords": "May",
"count": 2
},
{
"UserName": "Sarathy Devaraju",
"week": "Week 2",
"MeetingHash": "Hold/Uncategorized",
"monthinwords": "May",
"count": 3
},
{
"UserName": "Sarathy Devaraju",
"week": "Week 2",
"MeetingHash": "1st Presentation / Meeting",
"monthinwords": "Jun",
"count": 1
},
{
"UserName": "Sarathy Devaraju",
"week": "Week 1",
"MeetingHash": "Follow-On Meetings",
"monthinwords": "Jun",
"count": 1
},
{
"UserName": "Sarathy Devaraju",
"week": "Week 2",
"MeetingHash": "1st Presentation / Meeting",
"monthinwords": "May",
"count": 1
},
{
"UserName": "Sarathy Devaraju",
"week": "Week 3",
"MeetingHash": "Follow-On Meetings",
"monthinwords": "July",
"count": 1
},
{
"UserName": "Priya",
"week": "Week 1",
"MeetingHash": "Hold/Uncategorized",
"monthinwords": "May",
"count": 2
},
{
"UserName": "Priya",
"week": "Week 2",
"MeetingHash": "1st Presentation / Meeting",
"monthinwords": "Jun",
"count": 1
},
{
"UserName": "Priya",
"week": "Week 1",
"MeetingHash": "Follow-On Meetings",
"monthinwords": "Jun",
"count": 1
},
{
"UserName": "Priya",
"week": "Week 2",
"MeetingHash": "1st Presentation / Meeting",
"monthinwords": "May",
"count": 1
},
{
"UserName": "Priya",
"week": "Week 1",
"MeetingHash": "Follow-On Meetings",
"monthinwords": "July",
"count": 1
}
];
constWEEKS = ["Week 1", "Week 2", "Week 3", "Week 4"];
/*
const result = data.map(obj => {
return {
UserName: obj.UserName,
month: obj.monthinwords,
meetingHash: obj.MeetingHash,
Week1: WEEKS.indexOf(obj.week) == 0 ? obj.count : 0,
Week2: WEEKS.indexOf(obj.week) == 1 ? obj.count : 0,
Week3: WEEKS.indexOf(obj.week) == 2 ? obj.count : 0,
Week4: WEEKS.indexOf(obj.week) == 3 ? obj.count : 0,
}
}
);
*/const result = data.reduce((acc, obj) => {
existingObj = acc.find(ele => ele.UserName == obj.UserName && ele.month == obj.monthinwords && ele.meetingHash == obj.MeetingHash)
if (existingObj) {
existingObj.Week1 += WEEKS.indexOf(obj.week) == 0 ? obj.count : 0;
existingObj.Week2 += WEEKS.indexOf(obj.week) == 1 ? obj.count : 0;
existingObj.Week3 += WEEKS.indexOf(obj.week) == 2 ? obj.count : 0;
existingObj.Week4 += WEEKS.indexOf(obj.week) == 3 ? obj.count : 0;
} else {
acc.push({
UserName: obj.UserName,
month: obj.monthinwords,
meetingHash: obj.MeetingHash,
Week1: WEEKS.indexOf(obj.week) == 0 ? obj.count : 0,
Week2: WEEKS.indexOf(obj.week) == 1 ? obj.count : 0,
Week3: WEEKS.indexOf(obj.week) == 2 ? obj.count : 0,
Week4: WEEKS.indexOf(obj.week) == 3 ? obj.count : 0,
});
}
return acc;
}, []);
console.log(result);
Post a Comment for "Recreate A Json Response Based On Existing Response"