[英]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
: 我使用
moment
创建了从当年到1930年的整数下降数组:
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: 我正在尝试将
options
转换为对象数组,以便生成的数组是这样的:
[{value: '2018', label: '2018'}, {value: '2017', label: '2017'}, ..., {value: '2', label: '2'}, {value: '1', label: '1'}]
Just .map
each item to an object instead of to a single number: 只需将每个项目
.map
到一个对象而不是一个数字:
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>
What What you want is another map
. 你想要的是另一张
map
。 map
will always take an array of a given length in an order and produce another array of the same length in the same order (in JS). map
将始终按顺序获取给定长度的数组,并以相同的顺序生成相同长度的另一个数组(在JS中)。 So if we take your code and then add on: 因此,如果我们接受您的代码,然后添加:
options.map(o => o.toString).map(o => ({ value: o, label: o }))
you'd get get your objects. 你会得到你的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.