React (typescript): How to loop inside const creation
You can use Object.values
, Object.keys
or Object.entries
.
Object.values(fields).map(month => <Field {...month}/>)
If you want to separate the months, you can split the array in half (Object.values(fields)
) and render both separately.
render(){ const months = Object.values(fields) const halfwayThrough = Math.floor(months.length / 2) const monthFirstHalf = months.slice(0, halfwayThrough); const monthSecondHalf = months.slice(halfwayThrough, months.length); ... return ( ... <div className="col-md-3"> {monthFirstHalf.map(month => <Field {...month}/>)} </div> <div className="col-md-3"> {monthSecondHalf.map(month => <Field {...month}/>)} </div> ... )}
Edit:
Instead of having that huge object and supposing all the properties are the same except for the name, here is something you can do with .reduce
(you could also do with a .forEach
)
const months = ['Jan', 'Feb', 'Mar', /* ...rest */] const fields = months.reduce((monthObject, monthName) => { let monthId = monthName.toLowerCase() monthObject[monthId] = { id: monthId, label: monthName, editor: "dropdown", options: data, value: "hello", validation: {rule: required} } return monthObject}, {})
And with this, you will have created that huge object
Combining both thins, here is what you can do
const months = ['Jan', 'Feb', 'Mar', /* ...rest */] return ( ... {months.map(month => <Field id={month} label={month} editor: "dropdown", options: data, value: "hello", validation: {rule: required} /> )} ...)
If I understand correctly, you are thinking about refactoring the creation of a list of objects by looping over a list of month names. Vencovsky shows how to use reduce()
to do this. I would go a step further and create the <Field>
components directly by using map()
:
const months = ['Jan', 'Feb', 'Mar', /* ...rest */] const monthFields = months.map(m => <Field id={m} label={m} editor="dropdown" options={data} value="hello" validation={{rule: required}} />);