[英]How can i create an object keys from array values in javascript?
i am new to javascript and while working on a little project i have a problem , i have an array which contains the day splitted into quarters like that我是 javascript 新手,在做一个小项目时遇到了一个问题,我有一个数组,其中包含像这样分成几个季度的一天
['09:00', '09:15', '09:30', '09:45']
i want to create an object with keys that are the values of this array like that :我想创建一个对象,其键是该数组的值,如下所示:
var obj = {
'09:00': false ,
'09:15': true ,
'09:30': false
....
}
but i don't want to do it manually because the object will contain time until 00:00 so i will have to write a lot of code while i think it is possible to do it automatically , i tried fromEntries() method but it gives me a list of key value pairs when i want just to set the keys of the object .但我不想手动执行此操作,因为该对象将包含直到 00:00 的时间,因此我将不得不编写大量代码,而我认为可以自动执行此操作,我尝试了 fromEntries() 方法,但它给出了当我只想设置对象的键时,我会列出键值对列表。 Any solution ?任何解决方案?
You can simple use a for-loop
like:您可以简单地使用for-loop
如:
const arr = ['09:00', '09:15', '09:30', '09:45']; let obj = {}; for (var i = 0; i < arr.length; ++i) obj[arr[i]] = ''; console.log(obj);
I don't know the logic of true
and false
so i assigned an empty string
.我不知道的逻辑true
和false
,所以我分配了一个空string
。
Your intuition was good: Object.fromEntries() does the job.你的直觉很好: Object.fromEntries() 可以完成这项工作。
But you have to build an array like this:但是你必须像这样构建一个数组:
[['09:00',true ], ['09:30', true] /*...*/]
In order to do this, a simple .map() can help为了做到这一点,一个简单的.map()可以帮助
Object.fromEntries(
['09:00', '09:15', '09:30', '09:45'].map(hour=>[hour, true])
)
You can replace true
with getStatusFromHour(hour)
and then build a function that sets the right boolean to the selected hour.您可以将true
替换为getStatusFromHour(hour)
,然后构建一个函数,将正确的布尔值设置为选定的小时。
You can write a simple for loop and append the data to the object with the required state.您可以编写一个简单的 for 循环并将数据附加到具有所需状态的对象。 Like:喜欢:
var arr = ['09:00', '09:15', '09:30', '09:45', '10:00'];
var obj = {};
for(var i = 0; i < arr.length; i++) {
obj[arr[i]] = false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.