Merge objects based on specific property within an array of objects

Is there a way to merge objects based on one property and also add missing Days names in the output?

Consider this example:

var array =  [
       {
      "heure1": "14:00",
      "heure2": "17:00",
      "day": "Sunday",
    },
       {
      "heure1": "08:00",
      "heure2": "13:00",
      "day": "Sunday",
    },
       {
      "heure1": "14:00",
      "heure2": "16:00",
      "day": "Monday",
    },
       {
      "heure1": "08:00",
      "heure2": "18:00",
      "day": "Monday",
    },
  ];

Desired outcome:

var array =  [
       {
      "heure": ["14:00","17:00","08:00","13:00"],
      "day": "Sunday",
    },
     {
      "heure": ["14:00","16:00","08:00","18:00"],
      "day": "Monday",
    },
    {
      "heure": [],
      "day": "Saturday",
    },
    {
      "heure": [],
      "day": "Friday",
    },
    {
      "heure": [],
      "day": "Thursday",
    },
    {
      "heure": [],
      "day": "Wednesday",
    },
    {
      "heure": [],
      "day": "Tuesday",
    },

  ];

I have tried various Stack Overflow solutions without success. Any help would be appreciated. Thank you!

Answer №1

Attempting the Challenge

<script>
    var data = [{
            "start_time": "2:00 PM",
            "end_time": "5:00 PM",
            "day_of_week": "Sunday",
        },
        {
            "start_time": "8:00 AM",
            "end_time": "1:00 PM",
            "day_of_week": "Sunday",
        },
        {
            "start_time": "2:00 PM",
            "end_time": "4:00 PM",
            "day_of_week": "Monday",
        },
        {
            "start_time": "8:00 AM",
            "end_time": "6:00 PM",
            "day_of_week": "Monday",
        },
    ];
    var weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"];
    var output = [];
    weekdays.map(function (weekday) {
        var timesByDay = data.filter(function (element) {
            return weekday == element.day_of_week
        })
        if (timesByDay.length) {
            timeSlots = [];
            timesByDay.map(function (sched, i) {
                for (var prop in sched) {
                    if (timesByDay[0].hasOwnProperty(prop) && prop != "day_of_week") {
                        timeSlots.push(sched[prop])
                    }
                }
            })
            output.push({
                "weekday": weekday,
                "time_slots": timeSlots
            })
        } else {
            output.push({
                "weekday": weekday,
                "time_slots": []
            })
        }
    })
    console.log(output);
</script>

Answer №2

To start, create 7 entries representing each day of the week and initialize them with an empty array for the heure property.

Next, iterate through the original data, find the corresponding entry for each day, and add the specified times to the heure array.

It's important to note that in your input example, the property names for Day have different spellings (DAY, Day). It's recommended to use consistent lowercase formatting for property names.

Check out this implementation:

var array =  [{"heure1": "14:00","heure2": "17:00","day": "Sunday",}, {"heure1": "08:00","heure2": "13:00","day": "Sunday",}, {"heure1": "14:00","heure2": "16:00","day": "Monday",}, {"heure1": "08:00","heure2": "18:00","day": "Monday", },];

let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let obj = Object.fromEntries(days.map(day => [day, { heure: [], day }]));
for (let {heure1, heure2, day} of array) obj[day].heure.push(heure1, heure2);
let result = Object.values(obj);

console.log(result);

Answer №3

the path I follow...

var arr_1 = 
    [ { heure1: '14:00', heure2: '17:00', day: 'Sunday' } 
    , { heure1: '08:00', heure2: '13:00', day: 'Sunday' } 
    , { heure1: '14:00', heure2: '16:00', day: 'Monday' } 
    , { heure1: '08:00', heure2: '18:00', day: 'Monday' } 
    ] 

const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

const res = days.map(d=>
        {
        let r = { heure:[], day:d }
        arr_1.filter(x=>x.day===d)
             .forEach(({heure1,heure2})=> { r.heure.push(heure1,heure2) })
        r.heure.sort() 
        return r
        })


console.log( res  )
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Do we really need that specific structure for the result?

If not, by adjusting the structure of the result, you can achieve something similar to this:

const getHeureByDay = (heureArray) => {
  let output = {
    Sunday: { heure: [] },
    Monday: { heure: [] },
    Tuesday: { heure: [] },
    Wednesday: { heure: [] },
    Thursday: { heure: [] },
    Friday: { heure: [] },
    Saturday: { heure: [] },
  };
  
  heureArray.forEach((heureItem) => {
    Object.keys(heureItem).forEach((key) => {
      if (key !== "day") {
        output[heureItem.day].heure.push(heureItem[key]);
      }
    })
  });
  
  return output;
};

const heureArray = [
  {
    "heure1": "14:00",
    "heure2": "17:00",
    "day": "Sunday",
  },
  {
    "heure1": "08:00",
    "heure2": "13:00",
    "day": "Sunday",
  },
     {
    "heure1": "14:00",
    "heure2": "16:00",
    "day": "Monday",
  },
     {
    "heure1": "08:00",
    "heure2": "18:00",
    "day": "Monday",
  }
];

console.log(getHeureByDay(heureArray));

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

A guide to generating numerous SVG paths using a JavaScript function

Creating strokes with similar length but different angles of rotations can be achieved efficiently using JavaScript instead of writing redundant lines of code. The following code snippet demonstrates one way to achieve this: function stroke(rot) { var d ...

What is the technique to make a *ngFor render items in a random order?

I'm working on creating an application that needs to display elements in a random order. However, due to restrictions within the application, I am unable to modify the ngFor directive. How can I achieve displaying ngFor content randomly? ...

What is the best way to send information to a component using Props in Vue2?

Recently, I created a .Vue file to showcase information about a cafe on the Cafe Details Page. However, to streamline template updates, I decided to extract certain parts of this details page and turn it into its own component. This led me to create a new ...

Top method for filling an array with strings

Imagine having an array called 'newArray'. var newArray = []; You can add strings to it like this: var thisString = 'watch'; newArray.push(thisString); Now, if you want to have 50 instances of the 'thisString' in the newAr ...

You are only able to click the button once per day

I am working on a button that contains numeric values and updates a total number displayed on the page when clicked. I would like this button to only be clickable once per day, so that users cannot click it multiple times within a 24 hour period. Below i ...

Changing the close button icon in highslide popups

Utilizing highslide together with highcharts, I need to customize the functionality of the close button. Specifically, I want to trigger an additional function when a user clicks on the "X" button. Upon inspecting the "X" button, this is what appears in m ...

Is there a way to automatically convert a webpage to a PDF when it is requested?

I'm looking to convert the webpage into a PDF file upon request. Below are the scripts I am using: <script> pdfdoc.fromHTML($('#container').html(), 10, 10, { 'width': 110, ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

Simultaneous AJAX, animated page loader

My website takes 3 seconds to load due to multiple Synchronous AJAX requests. To enhance user experience, I would like to implement a loading page with an animated GIF. Once the Ajax requests are completed and the page is fully loaded, the loading page sh ...

Incorporating AJAX functionality into an existing PHP form

I am currently working on a PHP registration form that validates user inputs using $_POST[] requests. Validating username length (3-20 characters) Checking username availability Ensuring the username matches /^[A-Za-z0-9_]+$/ pattern and more... Instead ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

What's the best way to navigate across by simply pressing a button located nearby?

Hey there! I'm new to JavaScript and I'm working on a shopping list page for practice. In my code, I can add new items to the list, but what I really want is to be able to cross out an item when I click the "Done" button next to it, and then uncr ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

Creating an AJAX request in Play 2.x by using a shared button

Although I have successfully utilized AJAX requests in the past using a form and adding return false to prevent page refresh, I recently encountered an issue when moving my JavaScript into a separate file. The @ commands now fail, making it difficult for m ...

Using ng-repeat with deeply nested objects

I am facing an issue with rendering an object that contains comments along with replies objects that have nested replies objects. I attempted to use a solution from here, but it resulted in my replies object being undefined. For example, I tried the follow ...

What is the best method for converting input files into FormData?

I recently created a form that allows users to upload both an audio file and an image file simultaneously. However, during testing, I noticed that the alert only displays basic data and does not include the form data. function PodcastUpload({ data }) { ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

The issue arises when trying to enqueue a Javascript file, causing an error stating that $ is not

I am having an issue with my WordPress plugin development where the jquery dependency is not being pulled in correctly, despite passing it in the third parameter of the wp_enqueue_scripts function. Upon inspecting with Google Chrome, I encountered the erro ...