ckingchris
ckingchris

Reputation: 609

Javascript Switch Statement multiple cases return the values

I have a json object I am getting my data from with the values (Cow: 'Yes', Chicken: 'NULL') and (Cow: 'Yes', Chicken: 'Yes') etc. I would like to display only the values that have 'Yes' and then their value. Currently I only can return the first case that includes 'Yes', for example it just returns 'Cow', however the goal is to return 'Cow, Chicken' if both have the 'Yes' value. What am I doing wrong here? Or if there is a better method, thank you for your help.

switch ("Yes") {
    case popup.properties.Beef:   return "<span>Cows</span>";
    case popup.properties.Pork: return "<span>Pigs</span>";
    case popup.properties.Sheep:  return "<span>Sheep</span>";
    case popup.properties.Goat: return "<span>Goats</span>";
    case popup.properties.Lamb:  return "<span>Lambs</span>";
    case popup.properties.Rabbit: return "<span>Rabbit</span>";
    case popup.properties.OtherMeat:  return "<span>Other</span>";
    case popup.properties.Chicken: return "<span>Chicken</span>";
    case popup.properties.Turkey:  return "<span>Turkey</span>";
    case popup.properties.Duck: return "<span>Duck</span>";
    case popup.properties.Goose:  return "<span>Geese</span>";
    case popup.properties.Pheasant: return "<span>Pheasants</span>";
    case popup.properties.Quail:  return "<span>Quail</span>";
    case popup.properties.OtherPoultry:  return "<span>Other Poultry</span>";
    default:      return "";
}

Upvotes: 1

Views: 65

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386746

You could take an object with the wanted values and get an array of strings.

var values = { Beef: "Cows", Pork: "Pigs", Sheep: "Sheep", Goat: "Goats", Lamb: "Lambs", Rabbit: "Rabbit", OtherMeat: "Other", Chicken: "Chicken", Turkey: "Turkey", Duck: "Duck", Goose: "Geese", Pheasant: "Pheasants", Quail: "Quail", OtherPoultry: "Other Poultry" };
    result = Object
        .keys(popup.properties)
        .filter(k => popup.properties[k] === 'Yes')
        .map(k => values[k]);

Upvotes: 3

Related Questions