简体   繁体   English

Javascript - 如何创建对象数组,其中对象的键都具有相同的值

[英]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.

相关问题 如何将对象键分配给相同的属性并创建具有名称和值对的对象数组 - how to assign Object keys to a same property and create an array of objects with name and value pair-Javascript 有没有办法在 JavaScript 中创建一个 object,其中 object 键与用于值的变量同名? - is there a way in JavaScript to create an object where the object keys have the same name as the variables used for the value? 如何在所有对象的键相同且值可能不同的情况下将对象数组转换为单个 object - How can I convert an array of objects into single object while keys of all the objects are same and value may differ 将对象数组转换为单个 object,所有键的值都相同? - Turning an array of objects, into a single object with the same value for all keys? 使数组对象都具有相同的键 - Make array objects all have the same keys 如何从所有键都相同的数组中提取 object - how extract an object from an array where all of the keys are the same 当键相同时如何更新对象数组中的对象值 - How to update an object value in array of objects when the keys are same 通过javascript对象键创建对象数组 - Create array of objects from javascript object keys 合并两个具有相同键的对象数组,某些对象不会具有相同的值? - Merge two array of objects with same keys, some object won't have the same value? Javascript:数组中的所有对象都具有相同的属性 - Javascript: All Objects in Array Have Same Properties
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM