Dynamic creation of viewof options array

This is probably super simple but I usually work in Python and cannot figure out how to do this in JavaScript.

I have a map which maps values to labels:

  ['2017_Fall', 'Fall 2017'],
  ['2018_Spring', 'Spring 2018'],
  ['2018_Fall', 'Fall 2018'],
  ['2019_Spring', 'Spring 2019'],
  ['2019_Fall', 'Fall 2019'],
  ['2020_Spring', 'Spring 2020']

I would like to be able to use the map to dynamically create the options array for a viewof:

viewof semester= radio({
  title: 'Semester',
  options: [
    { label: 'Fall 2017', value: '2017_Fall' },
    { label: 'Spring 2018', value: '2018_Spring' },
    { label: 'Fall 2018', value: '2018_Fall' },
    { label: "Spring 2019", value: '2019_Spring' },
    { label: "Fall 2019", value: '2019_Fall' },
    { label: "Spring 2020", value: '2020_Spring' }
  value: '2017_Fall'

So instead of hardcoding the options, I would have a function that takes SEMSTER_TITLES as an input and returns the array of options.

I can think of how to do this in Python using list comprehensions but the JavaScript way is eluding me.

Like this?

viewof semester = radio({
  title: 'Semester',
  options: Array.from(SEMESTER_TITLES, ([value, label]) => ({value, label})),
  value: '2017_Fall'
1 Like

That is exactly it! I was missing the [] and {} around the value, label pairs. Thank you!

Here’s the canonical MDN page on ES6’s destructuring syntax:

1 Like