Is this possible?
I want to create continuous object data.
what i want
return [
{ text: '2', align: 'center', value: '2', sort: false },
{ text: '3', align: 'center', value: '3', sort: false },
{ text: '4', align: 'center', value: '4', sort: false },
{ text: '5', align: 'center', value: '5', sort: false },
{ text: '6', align: 'center', value: '6', sort: false },
{ text: '7', align: 'center', value: '7', sort: false },
{ text: '8', align: 'center', value: '8', sort: false },
]
my think
return [
() => {
for (let i = 0; i >= 8; i++) {
return {
text: i,
align: 'center',
value: i >= 10 ? `day${i}` : `day0${i}`,
sort: false,
}
}
},
]
But this, of course, did not work. How can I do it this way?
You can do this by filling an empty array of however many elements you want and then using map and the index of each empty item:
const result = new Array(35).fill(0).map((_, i) => ({
text: i,
align: 'center',
value: i >= 10 ? `day${i}` : `day0${i}`,
sort: false,
}));
console.log(result);
You can declare a small helper function that calls a function for (maps over) a given range of integers, like so:
function mapRange(min, max, fn) {
const out = [];
for (let i = min; i < max; i++) {
out.push(fn(i));
}
return out;
}
Then you can simply
const result = mapRange(0, 35, (i) => ({
text: i,
align: 'center',
value: i >= 10 ? `day${i}` : `day0${i}`,
sort: false,
}));
(According to a JSBench test, this is about 20% faster than Jamiec's similar solution using the new Array().fill().map() idiom.)
The other answers are too long... useless... Try
[...Array(7)].map((_, i) => ({ text: `${i+2}`, align: 'center', value: `${i+2}`, sort: false }));