Home > Net >  How to convert an object like this into a very specific array?
How to convert an object like this into a very specific array?

Time:11-12

{
  correct: "Warren Harding",
  incorrect: 
    0: "Theodore Roosevelt",
    1: "Andrew Jackson "
}

So I have this object, I want to turn it into an array containing objects like this:

[answerOptions: [{answerText: "Warren Harding", isCorrect: true}, {answerText: "Theodore Roosevelt", isCorrect: false}, {answerText: "Andrew Jackson", isCorrect: false}]

How can I do this because I have been trying to figure this out for so long but I can't figure it out.

CodePudding user response:

The OP literal is almost but not quite a valid object...

{
  correct: "Warren Harding",
  incorrect: 
    0: "Theodore Roosevelt",
    1: "Andrew Jackson "
}

Assuming the nested incorrect object is missing curly braces, a straight-forward answer looks like this (see the properly formed input in the snippet)...

// fix the input
const question = {
  correct: "Warren Harding",
  incorrect: {  // <- open curly
    0: "Theodore Roosevelt",
    1: "Andrew Jackson "
  } // <- close curly
}

// take a question with the above form and produce an array 
// of { answerText, isCorrect }
function optionsFromQuestion(question) {
  return [
    { answerText: question.correct, isCorrect: true },
    ...Object.values(question.incorrect).map(answerText => {
      return { answerText, isCorrect: false }
    })
  ]
}


const answerOptions = optionsFromQuestion(question)
console.log(answerOptions)

CodePudding user response:

Assuming your input object is actually like this:

data = { correct: "Warren Harding",
  incorrect: {
    0: "Theodore Roosevelt",
    1: "Andrew Jackson "
  }
} 

You can achieve your desired output with this:

result = { answerOptions: [
  { answerText: data.correct, isCorrect: true}, 
  ...Object.values(data.incorrect).map(x => ({ answerText: x, isCorrect: false }))
] } 
  • Related