Guide to transforming an array into a custom JavaScript object illustrating designated names for each key

Trying to utilize JavaScript to transform the given array into a JavaScript object, but unsure of the process.

The input array is structured such that each key corresponds to a day of the week (Sunday to Saturday); where key 0 represents Sunday, key 1 represents Monday, and so forth up to key 6 representing Saturday.

var times = [["8:30-12:00","14:00-18:00"],
["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],
["9:00-21:00"],[],[]];

The goal is to convert the above times array into the following JavaScript object:

timeObj = {
  sunday: [
    {
      start: '08:30',
      stop: '12:00'
    },
    {
      start: '14:00',
      stop: '18:00'
    }
  ],
  monday: [
    {
      start: '06:15',
      stop: '9:30'
    },
    {
      start: '13:00',
      stop: '16:00'
    },
    {
      start: '20:00',
      stop: '23:15'
    }
  ],
  tuesday: [],
  wednesday: [
    {
       start: '9:00',
       stop: '21:00'
    }
  ],
  thursday:  [
    {
       start: '9:00',
       stop: '21:00'
    }
  ],
  friday:  [],
  saturday:  []
};

What is the recommended method to achieve this transformation from the times array to the timeObj object?

Answer №1

To efficiently organize the schedule, you can use an array to represent each day and then iterate through it. During each iteration, you can add the corresponding day's time range to a result object.

var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
var result = {};

days.forEach((day, index) => {
  result[day] = times[index]
    .map(item => {
      let [start, stop] = item.split('-');
      return {start, stop};
    });
});

console.log(result);

Answer №2

If you want to optimize your code for managing 1-level lists, consider using Array.prototype.reduce. For 2-level lists, utilizing Array.prototype.map can help streamline the process of creating custom arrays within an object:

const data = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

const result = data.reduce((acc, item, index) => { 
  acc[days[index]] = 
    item.map(day => ({ 
      start: day.substr(0, day.indexOf('-')), 
      end: day.substring(day.indexOf('-') + 1)
    }));
  return acc;
 }, {});

Answer №3

Latest Update

This post contains a detailed discussion on software design and mathematics in providing the final answers at the top for easy reference.

Recommended Answer (for readability):

var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
var days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];

var timeObj = {};

for (var i = 0; i < times.length; i++)
{
    // Initialize an empty array:
    timeObj[days[i]] = [];

    // Add each timespan from the original array to this day
    for (var j = 0; j < times[i].length; j++)
    {
        var timespan = times[i][j];

        // Parse the string
        var timespanArr = timespan.split("-");
        var timespanObj = {
            start: ("0" + timespanArr[0]).substr(-5),
            end: ("0" + timespanArr[1]).substr(-5)
        };

        // Append to the respective day
        timeObj[days[i]].push(timespanObj);
    }
}

console.log(timeObj);

Compact Answer:

var times = [["8:30-12:00","14:00-18:00"],["6:15-9:30","13:00-16:00","20:00-23:15"],[],["9:00-21:00"],["9:00-21:00"],[],[]];
var start, end;
var obj = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].reduce((acc, el, idx) => (
    acc[el] = times[idx].map(span => (
        [start, end] = span.split("-"), {start, end}
    )), acc
), {});

The Challenge

While attempting to address two unique problems, it's essential to focus on:

  • Mapping indices to keys accurately
  • Parsing the given strings effectively

Creating understandable and easily maintainable code is key. Always prioritize human-readable code over complex one-liners for smooth future maintenance and development.

In Summary

Addressing software intricacies with clarity will lead to efficient coding practices and better outcomes. Stay focused on simplifying solutions and optimizing readability for long-term success in programming endeavors.

Answer №4

Here is the solution:

let dayList = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']

let workingHours = [
  ["8:30-12:00", "14:00-18:00"],
  ["6:15-9:30", "13:00-16:00", "20:00-23:15"],
  [],
  ["9:00-21:00"],
  ["9:00-21:00"],
  [],
  []
]

const schedule = {}
for (let index = 0; index < 7; index++) {
  const timeSlots = []
  schedule[dayList[index]] = timeSlots
  workingHours[index].forEach(interval => {
    const parts = interval.split('-')
    timeSlots.push({
      startTime: parts[0],
      endTime: parts[1]
    })
  })
}
console.log(schedule);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The routing in CakePhp 2.x seems to be malfunctioning

There is a link: localhost/issoisso/categories/getCategories/categoryId:486 However, I require this format: localhost/issoisso/categoria/486 The necessary code can be found here: gist.github.com/kleberksms/7756990 ...

In React JSX, what is the best approach for printing a substring?

I am facing an issue with dividing two variables in my React component. I need to display the result to only one decimal place, so I decided to use the substring method like this: <div className="col-md-8"> {(total_star / total_user).toString ...

Deciphering a JSON array by value or key

I have a JSON array that I need to parse in order to display the available locations neatly in a list format. However, I am struggling with where to start. The data should be converted to HTML based on the selected date. In addition, a side bar needs to s ...

Are the types identical but require direct conversion?

I'm encountering an issue with a table that stores an image as a byte array, or byte[0] if no image is provided by the user. cmd.Parameters.AddWithValue("@pic", string.IsNullOrEmpty(updateObj.image) ? new byte[0] : Convert.FromBase64String(updateObj. ...

A guide on using Jest.js to test labels within Vue 3 Quasar components by utilizing a forEach loop

Within my Vue Quasar component, a badge is implemented as shown below: <q-badge :color="green" text-color="white" :label="`${value.toFixed(2)}%`" /> The corresponding script is structured like this: <scri ...

Looking to conceal a JavaScript file or minimize it from the web browser following production build in React

Upon executing the npm run build command using the script provided in my React App's package.json file, "scripts": { "start": "react-scripts start", "build": "set 'GENERATE_SOURCEMAP=false&apos ...

What is the method for graphing data points that include two different y values?

I have been on the lookout for a solution to this question for quite some time now. While there are a few options that come close, I am yet to find the perfect answer. My goal is to create a line chart displaying water levels over time. I would like the d ...

Is it necessary to conceal the element every time the jQuery slideDown function is utilized?

Previously, I inquired about a certain matter related to this topic, but the response I received didn't provide a clear explanation. When pressing the 'duplicate' button on my form, instead of the input field simply appearing, I would prefe ...

Ways to conceal a message button on a website when a user logs out

I am looking for assistance with hiding the message button on my website after a user logs out. The message option should be disabled upon logout using a combination of Javascript and PHP. Can anyone help me with this issue? Below is the code for the butt ...

Select the correct nested div with the same name by clicking on it

My problem involves nested div elements with the same class. For example, I have a Panel inside another Panel. However, when I click on the inner panel, it is actually the outer panel that triggers the $(".panel").click function. What I need is for the ...

JavaScript: for each element in the array, print the current value

I'm working with an array of items and using a forEach loop. I need to extract the value of the current item in each iteration. Any suggestions on how I can achieve this? var bottom_array = [41,42,43,44] bottom_array.forEach(function(){ console.l ...

Steps to deactivate a ladda button

I'm currently utilizing Ladda UI for bootstrap in my project. My goal is to disable a button using jQuery after the user clicks on it. Despite attempting to use ajax OnComplete / OnSuccess / OnBegin, I've had no luck - the button remains enable ...

Discover the method to retrieve HTML content by sending an HTTP POST request in AngularJS, similar to loading content

My attempt to retrieve HTML content using Angular Js Post HTTP method was successful, but only for text contents like P tags. I am now trying to fetch HTML contents that include input types such as text boxes using Angular JS. Interestingly, when I utilize ...

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

Guide on inserting data into a table using a multidimensional array

I have a multidimensional array that looks like this after looping through it array(10) { ["id"]=> string(3) "482" ["firstname"]=> string(3) "Ian" ["lastname"]=> string(8) "Phillips" ["candidate_id"]=> string(3) "482" ...

Comparing the use of malloc for initializing a char pointer versus directly assigning a string to the char pointer

Trying to grasp the concept of memory allocation when it comes to char and strings. Understanding that a declared array's name is like a pointer to the first element, residing in the stack. Utilizing malloc allows for utilizing the heap, but initial ...

Display tab content in Vue.js upon clicking

I'm encountering an issue with my Vue.js code. I want to display specific content every time I click on a tab. Here's the code snippet I have written: <template> <nav class="horizontal top-border block-section"> <div class= ...

What distinguishes declaring an array within int main() from declaring it outside int main()?

CASE 1 #include <stdio.h> long long arr[10000005]; int main() { int n; int m; scanf("%d %d", &n, &m); int index1, index2, summand; for (int i = 0; i < n; i++) { arr[i] = 0; } while (m--) ...

What are the different techniques for implementing React-Redux? Comparing Redux-thunk and Redux-Saga

My understanding of Redux is still quite hazy as I delve into various techniques and methods. I am curious to learn about other methods similar to redux-Thunk and redux-saga. Each utilizes distinct functions such as CreateSlice. I am interested to know w ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...