I want to create array of object in javascript like interval manner which is dynamic like suppose interval value is 10 then it should start with 10 and end to 100
initial value = 10 end value = 100
so final array belike
[
{
"label": "10",
"value": "10"
},
{
"label": "20",
"value": "20"
},
{
"label": "30",
"value": "30"
},
{
"label": "40",
"value": "40"
},
{
"label": "50",
"value": "50"
},
{
"label": "60",
"value": "60"
},
{
"label": "70",
"value": "70"
},
{
"label": "80",
"value": "80"
},
{
"label": "90",
"value": "90"
},
{
"label": "100",
"value": "100"
}
]
so any idea how i can make array of object as above
You could also use Array.from() to generate the values.
We'd use a createLabels() function to wrap this, passing in a startValue, endValue and step.
function createLabels(startValue, endValue, step) {
const length = 1 + (endValue - startValue) / step;
return Array.from({ length }, (v,k) => {
const value = String(startValue + k*step);
return { label: value, value };
});
}
console.log(createLabels(10, 100, 10))
.as-console-wrapper { max-height: 100% !important; }
You can initialize your array like this :
[...Array(10).keys()].map(i => ({'label':10+i*10, 'value':10+i*10}))
If you want a more generic one :
const gen = (init,end,step) =>
([...Array(Math.ceil((end-init+1)/step)).keys()].map(i => ({
'label':init+(i)*step,
'value':init+(i)*step
})));
gen(10,100,10);