0

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 ?

4
  • 1
    I don't understand, true and false where did they come from? Commented Jun 17, 2021 at 11:11
  • true or false are not the problem i will get them with another method but my question is how to set the values of the array as the keys of the object Commented Jun 17, 2021 at 11:13
  • i tried fromEntries(). OK , then show what have you tried... Commented Jun 17, 2021 at 11:13
  • Does this answer your question? Convert array values to object keys Commented Jun 17, 2021 at 11:22

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.