What is the best way to create a loop for an array that holds objects?

Having an array with multiple objects raises a question.

var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
    ];

In this array, MODE along with several week days are distinguishable properties.

The aim is to organize MONDAY values under an array named MONDAY, TUESDAY values under TUESDAY, and so on. The key of each value should match the corresponding MODE (comfort, eco, etc).

To clarify:

var MONDAY =  ["Comfort":"09:00:00","ECO":"22:00:00", ...]
var TUESDAY = ["Comfort":"09:00:00","ECO":"22:00:00",...]

An attempt was made to filter the initial array

var comfort = profile.filter(p => p.MODE == "Comfort");
var eco = profile.filter(p => p.MODE == "Eco");
var standby = profile.filter(p => p.MODE == "Standby");



var comfortMode = comfort[0];
var ecoMode = eco[0];
var standbyMode0 = standby[0];
var standbyMode1 = standby[1];



console.log(ecoMode["MONDAY"]);
console.log(standbyMode0["MONDAY"]);

However, reaching a point where manual input seems necessary has caused a roadblock

    var MONDAY = [ecoMode["MONDAY"],comfortMode["MONDAY"],standbyMode0["MONDAY"],standbyMode1["MONDAY"]];
var TUESDAY  = [...,...,...,...]

Are there alternative methods for creating loops that arrange all MONDAY values from comfortMode, ecoMode, and other arrays into an array named MONDAY?

Answer №1

Here is a modified solution to address your issue. The format of the output has been adjusted:

var MONDAY =  ["Comfort":"09:00:00","ECO":"22:00:00", ...]
var TUESDAY = ["Comfort":"09:00:00","ECO":"22:00:00",...]

Instead of an array, it will now be an object with weekdays as keys.

{
  "MONDAY": [
    {
      "Comfort": "09:00:00"
    },
    {
      "Eco": "22:00:00"
    },
    {
      "Standby": "07:30:00"
    },
    {
      "Standby": "21:00:00"
    }
  ],
  ...
}

var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    ...
];

var weekdays = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"];

var finalResult = weekdays.reduce((acc, currentDay) => {
    var dayValues = profile.reduce((acc1, currentProfile) => {
        return [...acc1, {
            [currentProfile.MODE]: currentProfile[currentDay]
        }]
    }, []);

    return {
        ...acc,
        [currentDay]: dayValues,
    };
}, {});

console.log(finalResult);

Answer №2

If you're looking for a solution, here's one that may not be the most elegant but it definitely gets the job done and can serve as a good starting point.

var profile = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
    ];

    let monday = []
    let tuesday = []
    let wednesday = []
    let thursday = []
    let friday = []
    let saturday = []
    let sunday = []
    profile.forEach(e => {
        let mode = e.MODE
        let mondayVal = e.MONDAY
        let tuesdayVal = e.TUESDAY
        let wednesdayVal = e.WEDNESDAY
        let thursdayVal = e.THURSDAY
        let fridayVal = e.FRIDAY
        let saturdayVal = e.SATURDAY
        let sundayVal = e.SUNDAY
        monday.push({[mode]: mondayVal})
        tuesday.push({[mode]: tuesdayVal})
        wednesday.push({[mode]: wednesdayVal})
        thursday.push({[mode]: thursdayVal})
        friday.push({[mode]: fridayVal})
        saturday.push({[mode]: saturdayVal})
        sunday.push({[mode]: sundayVal})
    })

console.log("Monday: ", monday)
console.log("Tuesday: ", tuesday)
console.log("Wednesday: ", wednesday)
console.log("Thursday: ", thursday)
console.log("Friday: ", friday)
console.log("Saturday: ", saturday)
console.log("Sunday: ", sunday)

If you have any doubts or need clarification on anything, feel free to reach out.

Answer №3

To obtain an array of hours for each day, you can use the following methods:

let schedule = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
];

// Initialize an object to store the arrays
let dailyHours = {}

schedule.forEach(item => {
  // Store the mode value
  let mode = item.MODE;
  
  // Loop through each attribute in the object
  for (let key in item) {
    // Do not include the MODE attribute
    if (key !== "MODE") {
      // Create the array for the day if it doesn't exist 
      if (typeof dailyHours[key] === "undefined") {dailyHours[key] = [];}
      // Add the current value to the array
      dailyHours[key].push(item[key]);
    }
  }
})

// Display the final object
console.log(dailyHours)

Alternatively, if you want to preserve the mode information, you can use this method:

let schedule = [
    {"MODE":"Comfort","MONDAY":"09:00:00","TUESDAY":"09:00:00","WEDNESDAY":"09:00:00",
    "THURSDAY":"09:00:00","FRIDAY":"09:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Eco","MONDAY":"22:00:00","TUESDAY":"22:00:00","WEDNESDAY":"22:00:00",
    "THURSDAY":"22:00:00","FRIDAY":"22:00:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"07:30:00","TUESDAY":"07:30:00","WEDNESDAY":"07:30:00",
    "THURSDAY":"07:30:00","FRIDAY":"07:30:00","SATURDAY":null,"SUNDAY":null},
    {"MODE":"Standby","MONDAY":"21:00:00","TUESDAY":"21:00:00","WEDNESDAY":"21:00:00",
    "THURSDAY":"21:00:00","FRIDAY":"21:00:00","SATURDAY":null,"SUNDAY":null}
];
// Initialize an object to store the arrays
let hourlySchedule = {}

schedule.forEach(item => {

  // Capture the mode value
  let mode = item.MODE;
  
  // Loop through each attribute in the object
  for (let key in item) {
    // Do not include the MODE attribute
    if (key !== "MODE") {
      // Create the nested objects if they don't exist 
      if (typeof hourlySchedule[key] === "undefined") {hourlySchedule[key] = {};}
      
      // Create the array for the mode if it doesn't exist 
      if (typeof hourlySchedule[key][mode] === "undefined") {hourlySchedule[key][mode] = []}
      
      // Add the current value to the array
      hourlySchedule[key][mode].push(item[key]);
    }
  }
  
})

// Display the final object
console.log(hourlySchedule)

These approaches allow you to expand your initial array effortlessly.

Answer №4

If you want to efficiently group items from the input array and aggregate the desired output, consider utilizing Array.prototype.reduce.

var data=[{MODE:"Comfort",MONDAY:"09:00:00",TUESDAY:"09:00:00",WEDNESDAY:"09:00:00",THURSDAY:"09:00:00",FRIDAY:"09:00:00",SATURDAY:null,SUNDAY:null},{MODE:"Eco",MONDAY:"22:00:00",TUESDAY:"22:00:00",WEDNESDAY:"22:00:00",THURSDAY:"22:00:00",FRIDAY:"22:00:00",SATURDAY:null,SUNDAY:null},{MODE:"Standby",MONDAY:"07:30:00",TUESDAY:"07:30:00",WEDNESDAY:"07:30:00",THURSDAY:"07:30:00",FRIDAY:"07:30:00",SATURDAY:null,SUNDAY:null},{MODE:"Standby",MONDAY:"21:00:00",TUESDAY:"21:00:00",WEDNESDAY:"21:00:00",THURSDAY:"21:00:00",FRIDAY:"21:00:00",SATURDAY:null,SUNDAY:null}];

var outcome = data.reduce((compiled, element) => {

    Object.keys(element).filter(key => key !== 'MODE').forEach(key => compiled[key].push({[element.MODE]: element[key]}));

    return compiled;

}, { MONDAY:[], TUESDAY:[], WEDNESDAY: [], THURSDAY:[], FRIDAY:[], SATURDAY:[], SUNDAY:[] });

console.log(outcome);

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

JQuery's animations and their influence on element positioning

My thumbnail animation increases in size on hover, but it is affecting the position of the other images. The issue is that when hovering over an image, the others move down and to the right to make space for the animated one. I want the other images to st ...

In C++, a recurring pattern of local array elements repeats within a loop

Within the context of the following loop, there exists a local char array called current_name. I opted to declare it within the loop itself in order to enable changes each time a new line is read from a file. However, an issue arises where the previous dat ...

Exploring the connection between two MongoDB collections

I currently have two collections in my MongoDB database: Category and Book Here is the category.js code: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var categoryModel = new Schema({ catName: String, menuKey: String }); module.ex ...

Submitting form data in Angular is a straightforward process

I'm currently using the ng-flow library to upload images to my server. After a user drags and drops an image, I can successfully retrieve the HTML 5 file image in my controller. However, when trying to download it to the server along with other parame ...

Defining variables in Typescript

Encountered an error message stating "Cannot re-declare variable 'greet' with scope 'Block'." My journey into learning Typescript hit a roadblock when I declared a variable along with its type, only to receive this error upon running t ...

HTTPInterceptor failing to capture incoming HTTP requests from external widget in Angular

Within my application, I incorporate a third-party UI widget obtained from the npm registry as a dependency. This widget makes a GET request using the axios module when integrated into my app's user interface. However, I have observed that the HTTP G ...

Assign a boolean value of true if a specific number (or numbers) is present in a list of numbers

So I have a situation where I need a boolean to be true only if it matches one of the undesirable numbers in my fruit array. This is what I've come up with: Below is the pseudo code snippet: public class FruitTypes { public static int[] fruit = new ...

Transferring Information to and from a Dynamic Link Library using C#

In the process of developing a C# program, my aim is to pass data to a C/C++ DLL, store the data, perform calculations on it, and then return the results to the C# program. The reason behind not using C# for the calculations is that I intend to enhance it ...

What is the best method for managing file storage and retrieval in web applications that only run on the client-side?

I'm currently working on an application where users can create their own data. Without a backend or database, all the information is stored within the user's session. My preferred solution involves: User interacts with the app, clicks "Save", ...

Change the direction of the div animation from horizontal to vertical

I have a bunch of divs with fixed dimensions that float horizontally, but I want them to animate vertically once one of them is clicked. Looking for a simple plugin or some code help! Example: |-------| |-------| |-------| | 1 | | 2 | | 3 | ...

Tips for querying multiple elements that share a common ID and verifying if the input has been modified

I have a series of text inputs that share a common id prefix but differ slightly at the end. Whenever a user enters text in any of these input fields, I want to trigger a function. Currently, I have this functionality implemented with the following code: ...

What should you do when the server is taking a while to respond?

I am in the process of creating a webpage that involves interactions between users, and I could use some guidance. Let's consider this hypothetical scenario: Client A visits a 'public' webpage and clicks a button. Client A then waits for a ...

Tips to prevent browser from freezing while creating a large number of HTML elements

I am currently utilizing Selection.js to develop a customizable grid on my website. To make this work effectively, I need a specific number of div elements to establish the selectable area. In my scenario, I generate all the divs using a for loop and then ...

Tips for updating images on the second page after clicking on a link from the first page using JavaScript

I need help with a website issue involving two pages. Page 1 features a few images, while page 2 contains another set of images. My goal is to change all the images on page 2 when a specific image on page 1 is clicked. I am able to redirect to page 2 succe ...

Utilizing the output of a callback function to execute res.render in a NodeJS application

Currently, I am utilizing oracledb for node in order to retrieve data from the database. Once the data is fetched, my goal is to transmit it to the client side using render() in express JS. Below is an example of the code structure: config.js module.expo ...

Restricting the number of items allowed in an ajax request

I need to retrieve information from a json file in order to populate a table. I only want to request a maximum of 5 items. jQuery.getJSON("data/data.json", function(data) { var table = $("table"); $.each(data, function(id, elem) { table.ap ...

Issue encountered while trying to execute Reapp project demo

As I embark on setting up my initial Reapp project, I encounter a roadblock right at the start. A blank screen greets me, accompanied by a console error stating that main.js is not found (error 404). Upon executing reapp run -d, the following errors manif ...

Using Vue.js for handling events with the passing method

As a newcomer to Vue.js, I am currently trying to understand method event handling. My goal is to read a barcode using input from a web camera and display its raw content. The function works perfectly if I just render the raw content. However, when I att ...

How can you pass an authorization token in a Next.js post request when using Django REST framework?

Is there a way to successfully pass a Django authorization token in Next.js using Axios? I attempted this method, but encountered a 404 error. let token = "Token 8736be9dba6ccb11208a536f3531bccc686cf88d" await axios.post(url,{ headers ...

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...