-3

How can I do a for with the array? and not doing it as I have it is not optimal, because it is a manual method and I want to optimize it

const choices = [
  { id: '1', name: '1' },
  { id: '2', name: '2' },
  { id: '3', name: '3' },
  { id: '4', name: '4' },
  { id: '5', name: '5' },
  { id: '6', name: '6' },
  { id: '7', name: '7' },
  { id: '8', name: '8' },
  { id: '9', name: '9' },
  { id: '10', name: '10' },
  { id: '11', name: '11' },
  { id: '12', name: '12' },
  { id: '13', name: '13' },
  { id: '14', name: '14' },
  { id: '15', name: '15' },
  { id: '16', name: '16' },
  { id: '17', name: '17' },
  { id: '18', name: '18' },
  { id: '19', name: '19' },
  { id: '20', name: '20' },
  { id: '21', name: '21' },
  { id: '22', name: '22' },
  { id: '23', name: '23' },
  { id: '24', name: '24' },
  { id: '25', name: '25' },
  { id: '26', name: '26' },
  { id: '27', name: '29' },
  { id: '28', name: '28' }
]
<SelectInput label='Día de corte' source='cutOffDay'
        choices={choices} />

I want to do something like this

const choices = []
const array = (choices) => {
  for(i = 0; i < 28; i++){
  choices = { id: i, name: i }
}

2 Answers2

0

You have to use the push method to add an object for each index in your array

const getChoices = () => {
    const choices = []
  for(let i = 1; i <= 28; i++){
    choices.push({ id: i, name: i });
  }
  return choices;
}

<SelectInput label='Día de corte' source='cutOffDay'
        choices={getChoices()} />
Tnc Andrei
  • 1,005
  • 10
  • 16
-1

If you want to dinamically add items to a select, there are several ways, but for your context this will do :

Html :

<select label='Día de corte' id='cutOffDay'/>

Javascript :

const choices = [
  { id: '1', name: '1' },
  { id: '2', name: '2' },
  { id: '3', name: '3' },
  { id: '4', name: '4' },
  { id: '5', name: '5' },
  { id: '6', name: '6' },
  { id: '7', name: '7' },
  { id: '8', name: '8' },
  { id: '9', name: '9' },
  { id: '10', name: '10' },
  { id: '11', name: '11' },
  { id: '12', name: '12' },
  { id: '13', name: '13' },
  { id: '14', name: '14' },
  { id: '15', name: '15' },
  { id: '16', name: '16' },
  { id: '17', name: '17' },
  { id: '18', name: '18' },
  { id: '19', name: '19' },
  { id: '20', name: '20' },
  { id: '21', name: '21' },
  { id: '22', name: '22' },
  { id: '23', name: '23' },
  { id: '24', name: '24' },
  { id: '25', name: '25' },
  { id: '26', name: '26' },
  { id: '27', name: '29' },
  { id: '28', name: '28' }
]
const options = choices.map(c => { return `<option id=${c.id} value=${c.name}>${c.name}</option>`})
document.getElementById('cutOffDay').innerHTML = options.join();
Mojimi
  • 2,561
  • 9
  • 52
  • 116
  • The question is about React, and it's not recommended to use `document.getElementById`. You should use the `render()` method – reisdev Dec 04 '18 at 15:58