1

in particular I want to access answer's numerical value, so that later on to sum them up.

previously tried length, which is not working for objects.

here is my data:

const qData = [
    {
        id: 0,
        question: "question 1",
        answers: [
            { value: 1, text: "rafael" },
            { value: 2, text: "dontaelo" },
            { value: 3, text: "leonardo" },
            { value: 4, text: "michelangelo" }
        ]
    },
    {
        id: 1,
        question: "question 2",
        answers: [
            { value: 1, text: "rafael" },
            { value: 2, text: "dontaelo" },
            { value: 3, text: "leonardo" },
            { value: 4, text: "michelangelo" }
        ]
    }
];

export default qData;

I attempted to sum the answer values like so:

handleShowScore = () => {
  var i, newScore;
  var a = qData.answers;

  for (i = 0; i < a.length; i++) {
    newScore = newScore + a[i].value;
  }
}
PinkFloyd
  • 25
  • 6

3 Answers3

0

The sample below does what you want, if I understood your question correctly

// Loop through all questions. Each question is stored in "q".
qData.forEach((q) => {
  console.log('qData:', q);
​
  // Make an array of all answer values   
  const answerValues = q.answers.map((a) => {
     return a.value;
  });
  console.log('answerValues:', answerValues);
​
  // Sum all answer values together
  const totalValues = answerValues.reduce((a, b) => a + b, 0)
  console.log('totalValues: ', totalValues);
});

If you want to have the sum of a specific ID

// Find specific ID.
const question = qData.find((q) => q.id === 0);

// Make an array of all answer values   
const answerValues = question.answers.map((a) => {
   return a.value;
});
console.log('answerValues:', answerValues);

// Sum all answer values together
const totalValues = answerValues.reduce((a, b) => a + b, 0)
console.log('totalValues: ', totalValues);
Joel'-'
  • 652
  • 1
  • 5
  • 17
  • thanks Joel for answering my question! Solution from 3limin4t0r suits better to my particular problem. have a great day! – PinkFloyd Jul 07 '20 at 14:34
0

qData is an array and doesn't have the property answers, so qData.answers will not work and return undefined.

You first have to loop over the questions, then in each question you'll have to loop over the answers:

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

let sum = 0;
for (const question of qData) {
  for (const answer of question.answers) {
    sum += answer.value;
  }
}

console.log(sum);

You could do this reduce the amount of loops if you use flatMap. Pulling up the answers into one large array.

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

const answers = qData.flatMap(question => question.answers);

let sum = 0;
for (const answer of answers) {
  sum += answer.value;
}

console.log(sum);

Instead of using a for loop to sum the values you could also use reduce, which iterates over an array reducing it to a single value.

const qData = [{id:0,question:"question 1",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]},{id:1,question:"question 2",answers:[{value:1,text:"rafael"},{value:2,text:"dontaelo"},{value:3,text:"leonardo"},{value:4,text:"michelangelo"}]}];

const answers = qData.flatMap(question => question.answers);
const sum = answers.reduce((sum, answer) => sum + answer.value, 0);

console.log(sum);
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • thank you for taking time and answering my question! it worked perfectly. I just tailored for my particular problem. handleShowScore = () => { const answers = document.querySelectorAll("select"); let newScore = 0; for (const answer of answers) { newScore = newScore + parseInt(answer.value, 10); } this.setState({ score: newScore }); }; – PinkFloyd Jul 08 '20 at 13:20
0

It's kind of a quiz, right? Let's assume my answers are:

const myAnswers = [{question: 'question 1', myAnswer:'rafael'},{question: 'question 2', myAnswer:'dontaelo'}]

I should have 1 point from the first question, and 2 from the second. We need to go through 2 loops: 1 to find the corresponding question, 1 to find the corresponding number of points:

const myPoints = myAnswers.map(answer => qData.find(question => question.question === answer.question).answers.find(possibleAnswer => possibleAnswer.text === answer.myAnswer).value)

Thats gives me [ 1, 2 ]. Now we need to to the sum with reduce:

const reducer = (accumulator, currentValue) => accumulator + currentValue;
const myScore = myPoints.reduce(reducer, 0);

I have 3 points ;-)

Fabien Lebas
  • 503
  • 7
  • 19