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

Modify the variable for each VU in K6 (refresh token)

When I start my K6 test, I utilize my setup() function to obtain a token that will be used by every VU. I want each VU to have the same token, rather than generating individual tokens for each one. Although this works fine initially, the challenge arises ...

What is the best way to invoke a custom hook that returns a value within the useEffect hook?

I have a unique situation where I am using a custom hook that returns an object based on the parameter it receives. I now need to modify this behavior by recreating the object with updated parameters within the useEffect function. The challenge is that I c ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

The Ultimate Guide to Initializing Variables in UI Router State Access

In my application, I have defined 2 states. One is "tickets" which matches /tickets ... $stateProvider // defines the states of my application .state("tickets", { // assigns properties to each state url: "/tickets", // route templateUrl: "m ...

What is the process for updating the URL for specific functions within $resource in Angular?

Check out this code snippet: angular.module('app.posts.services', []).factory('Post', ['$resource', 'API_ENDPOINT', ($resource, API_ENDPOINT) => $resource(API_ENDPOINT, { id: '@id' }, { updat ...

Keeping data external to promises in protractor

In my angular app, I have a timeline feature that displays the names and descriptions of players. All player names are under the common class player-title.ng-binding, while all player descriptions share the class .player-description.ng-binding To retrieve ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

What are some effective ways to integrate the WordPress API with ReactJS?

Wordpress recently introduced an API that allows you to make HTTP requests without worrying about routes, as the backend is handled for you. I'm curious, how can I integrate ReactJs with Wordpress API? This has been a frustrating challenge for me be ...

Exploring Sanity npm package with Jest for mocking tests

I am encountering an issue with mocking some code in my sanity.ts file: import sanityClient from '@sanity/client'; // eslint-disable-next-line @typescript-eslint/no-var-requires const blocksToHtml = require('@sanity/block-content-to-html&ap ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

Retrieving elements within an object using jQuery

Here's some code I'm working on: function popAreaTree() { var tree = $("ol.tree"); var list1 = tree.children('li'); var list2 = list1.children('ol').children('li'); $(tree).on(&apo ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

What is the appropriate response to send to the user in a web application?

I am currently developing a web application that utilizes AngularJS for the frontend, a REST API, and MongoDB as the backend, all powered by Node.js. Background to the challenge: One key requirement is to authenticate users using token-based authenticati ...

What is the best way to iterate through an array containing multiple objects in order to create a graph?

My API response contains multiple objects organized in an array: [{"symbol":"AAPL","date":"2020-02-27","adj_close":68.24}, {"symbol":"TSLA","date":"2020-02-27","adj_close":133.8}, {"symbol":"TSLA","date":"2020-02-28","adj_close":122.3}, {"symbol":"AAPL" ...

React: When an array state is controlling my components, why aren't they re-rendering?

I am facing an issue with my app where the className of buttons is not updating correctly when clicked. It seems that only active buttons trigger a re-render, while non-active ones do not. This behavior is confusing to me. Here's the code snippet for ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...

Uncover and control nested objects in JSON data

Having a dynamic foo object with the possibility of nested parent objects raises the question of how to effectively: 1) Determine the last object that has a parent? 2) Create an array containing all nested parent objects along with the initial obj (foo.o ...

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

Disabling the authentication prompt in the browser

Apologies for the repetition, but I would like to pose a more general question. Is there any method on the client side of a web application to predict if requesting a resource will result in a 401 status code and trigger an unattractive authentication pro ...