skip to Main Content

I have a quiz in react app now I want to send data in specific format as given below:-

{
    "ques": [
        {
            "res": "one"
        },
        {

            "res": "two"
        }
]
}

My Code:-
Sanbox URL

You can check console after click on next button of each question.
currently I’m getting in different format like

[
    "one",
    "two"
]

Thanks for your efforts!

2

Answers


  1. const formattedArray = ['one','two'].map(item => {return {res: item}})
    
    const result = {
         ques: formattedArray,
    }
    return result;
    

    Is this helpful?

    Login or Signup to reply.
  2. You just need to change the setSelectedAnswers

    change this :

    setSelectedAnswers((prevAnswers) => {
          const newAnswers = [...prevAnswers];
          newAnswers[index] = answer;
          return newAnswers;
        });
    
    

    and

    if (prevAnswers.includes(answer)) {
            return prevAnswers.filter((e) => e !== answer);
          } else {
            return [...prevAnswers, answer];
          }
    

    by this :

    setSelectedAnswers((prevAnswers) => {
          const newAnswers = [...prevAnswers];
          newAnswers[index] = {answer};
          return newAnswers;
        });
    
    

    and

    if (prevAnswers.includes(answer)) {
            return prevAnswers.filter((e) => e !== answer);
          } else {
            return [...prevAnswers, {answer}];
          }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search