Craig
Craig

Reputation: 133

JavaScript If Statement

I use this code below to parse JSON DATA. Is there a mod to this code that i could use before the ' as ' + entries.credits.cast[actor].character); in case there is not a character listed? That way it could look something like actor 1 as character 1, actor 2, actor 3 as character 3

var acting = [];
var maxCount = 5;
var count = entries.credits.cast.length;
if(count > maxCount) count = maxCount;
for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + ' as ' + entries.credits.cast[actor].character);
}

document.getElementById('cast').innerHTML = acting.join(', ');

Upvotes: 0

Views: 64

Answers (2)

Peter Abolins
Peter Abolins

Reputation: 1539

What about using the ternary operator?

for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + (entries.credits.cast[actor].character ? ' as ' + entries.credits.cast[actor].character : "");
}

Upvotes: 2

bits
bits

Reputation: 8340

You can use the Conditional Ternary Operator

for (var actor = 0; actor < count; actor++) {
    acting.push(entries.credits.cast[actor].name + (entries.credits.cast[actor].character  ? ' as ' + entries.credits.cast[actor].character : ''));
}

Upvotes: 1

Related Questions