0

I would like to have a function called getSelectedValues which retrieves data from the options array instead of a variable called SelectedValues ( which is the way I have it now). The variable Selected Values currently gets the values that are true inside of the options array and assigns them to itself. I simply would like to make this a function instead. (something called getSelectedValues I would imagine) How do I achieve this?

var options = [
{
name: "Red Pepper",
"selected": false,
value: "5.99"   
},
  {
name: "Garlic",
"selected": true,
value: "5.99"   
},
      {
name: "Tomatoes",
"selected": true,
value: "5.99"   
}, 
]


  var SelectedValues = options.filter(function (option) {
  return (option.selected);
  });
 console.log(SelectedValues)
evan
  • 117
  • 1
  • 10
  • [Duplicate]: https://stackoverflow.com/questions/1925976/declaring-functions-in-javascript – xdeepakv Apr 04 '20 at 02:26
  • you want to know how to write a function that takes an options array and filters them on selected property? – Ja͢ck Apr 04 '20 at 02:29

3 Answers3

0

Just for reference, read more:

Declaring functions in JavaScript

function filterOptions(options) {
  return options.filter(i => i.selected);
}

function filterOptions(options) {
  return options.filter((i) => i.selected);
}
var options = [
  {
    name: "Red Pepper",
    selected: false,
    value: "5.99",
  },
  {
    name: "Garlic",
    selected: true,
    value: "5.99",
  },
  {
    name: "Tomatoes",
    selected: true,
    value: "5.99",
  },
];

var selectedValues = filterOptions(options);
console.log(selectedValues);
.as-console {
  min-height: 100% !important;
}

.as-console-row {
  color: blue !important;
}
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

Something like this?

function getSelectedValues(options) {
  const size = Object.keys(options).length;
  for (var i = 0; i < size; i = i + 1) {
    const isSelected = options[i]["selected"];
    if (isSelected) {
      alert(options[i].name);
    }
  }
}

Jsfiddle here: https://jsfiddle.net/z3nrh8Ly/50/

-1
function getSelectedValues() {
   return options.filter(t => t.selected);

}

another way:

getSelectedValues = () => options.filter(t => t.selected);
Segev -CJ- Shmueli
  • 1,535
  • 14
  • 15
  • What if I didn't simply want to return the selected item but i then wanted to write a conditional statement stating if there were 3 or more that were selected than the price is 5. How would I write that? Something like function `getSelectedValues() { return options.filter(t => t.selected)` if(getSelectedValues length is 3 `.map(option => ({ name: option.name, value: 5 }));` } – evan Apr 04 '20 at 02:55