SURVEY DATA Each object is a survey which can have up to 10 questions and up to 5 different responses.
const allSubmittedSurveysData:{}[] = [
{
surveyGUID:'1234',
q1ID: '0001',
q1Response:'Very Satisfied',
q2ID: '0002',
q2Response:'Very Happy',
q3ID: '0003',
q3Response:'Satisfied',
q4ID: '0004',
q4Response:'Very Satisfied',
q5ID: '0005',
q5Response:'Very Satisfied',
q6ID: '0006',
q6Response:'Very Satisfied',
q7ID: '0007',
q7Response:'Very Satisfied',
q8ID: '0008',
q8Response:'Very Satisfied',
q9ID: '0009',
q9Response:'Very Satisfied',
q10ID: '0010',
q10Response:'Very Satisfied',
},
{
surveyGUID:'1235',
q1ID: '0001',
q1Response:'Satisfied',
q2ID: '0002',
q2Response:'Unhappy',
q3ID: '0003',
q3Response:'Dissatisfied',
q4ID: '0004',
q4Response:'Dissatisfied',
q5ID: '0005',
q5Response:'Very Satisfied',
},
{
surveyGUID:'1236',
q1ID: '0001',
q1Response:'Dissatisfied',
q2ID: '0002',
q2Response:'Neutral',
q3ID: '0003',
q3Response:'Satisfied',
q4ID: '0004',
q4Response:'Very Dissatisfied',
q5ID: '0005',
q5Response:'Very Satisfied',
},
]
let responseCounts: Record<string, any> = {}
allSubmittedSurveysData.forEach((survey: Record<string,any>) => {
Object.keys(survey).forEach(key => {
if(key!=='surveyGUID') {
let questionKey = key.replace('Response', 'ID')
let responseKey= key.replace('ID','Response')
if(!Object.keys(responseCounts).includes(survey[questionKey])){
responseCounts[survey[questionKey]]={}
}
if(!Object.keys(responseCounts[survey[questionKey]]).includes(survey[responseKey])){
responseCounts[survey[questionKey]][survey[responseKey]]= 1
} else{
++responseCounts[survey[questionKey]][survey[responseKey]]
}
}
})
})
Example expected output:
responseCounts= {
0001:{
Very Satisfied:1,
Satisfied:1,
Dissatisfied:1
},
0002:{...},
0003:{...},
etc
}
I'm making a 'responseCounts' object which will have an object for each question ID. Within each question ID object I've made the response the key and in the first instance if the "responseCounts'" keys does not include the response, the key is made and given 1 as the value. In the subsequent loop I'm expecting it to add one if the response is already a key in the object and the response is given again. The if condition is working as expected. The else is taking the value and doubling it instead of adding one each time the condition is met.
You are actually adding it twice, once for the ID
key and once for the Response
key.
Compare your version
if(key!=='surveyGUID') {
let questionKey = key.replace('Response', 'ID')
let responseKey= key.replace('ID','Response')
with this:
if(key!=='surveyGUID' && key.includes('Response')) {
let questionKey = key.replace('Response', 'ID')
let responseKey= key