简体   繁体   中英

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

['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 . Any solution ?

You can simple use a for-loop like:

 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 .

Your intuition was good: Object.fromEntries() does the job.

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

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.

You can write a simple for loop and append the data to the object with the required state. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM