mercredi 30 novembre 2016

javascript: setting default value with IF statement instead of OR

I'm only sharing a small bit of code because there is so much going on, and I hope this is enough to answer my question.

I have some existing JS where a value is determined with an OR statement and I think I need to convert that to an IF statement. The final output is currently giving me both values if they both exist, and I only want "question" where both "question" and "name" values exist.

var question = new fq.Question(questionData.answerId, topicId,
        questionData['question'] || questionData['name'],
        questionData['text']);

Instead of using the OR operator (answerData['question'] || answerData['name']), I'd like to do something similar to the following:

if (questionData['question'] is undefined) {
  use questionData['question'];
} else { 
  use instead questionData['name'] 
}

But, I don't know how I might accomplish such a statement within the () in the existing code pasted above. The name variable/value is always present, so there's no risk in defaulting to that. Question is only defined some of the time. And I don't ever want both appearing.

This is probably outside of the scope of my query here, but to fill in a little more detail, this code eventually outputs JSON files for topics and questions. Topics only have names values, and questions have both names and questions, but I only want the questions json to include questions values, not names. I'm pretty sure this is the key part in all of the JS to determin

Aucun commentaire:

Enregistrer un commentaire