Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - how to create an array of objects where the object's keys all have the same value

I created a descending array of integers from the current year to 1930 using moment:

options = Array(moment().year() - 1929).fill().map((_, index) => moment().year() - index)

I'm trying to convert options into an array of objects such that the resulting array is something like this:

[{value: '2018', label: '2018'}, {value: '2017', label: '2017'}, ..., {value: '2', label: '2'}, {value: '1', label: '1'}]
like image 676
Bargain23 Avatar asked Jul 11 '26 03:07

Bargain23


1 Answers

Just .map each item to an object instead of to a single number:

const options = Array(moment().year() - 1929)
  .fill()
  .map((_, index) => {
    const value = moment().year() - index;
    return { value, label: value };
  });
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
like image 170
CertainPerformance Avatar answered Jul 13 '26 17:07

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!