简体   繁体   中英

How do I rewrite an instantiation to a function?

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)

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; }

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/

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

}

another way:

getSelectedValues = () => options.filter(t => t.selected);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM