Tips on changing the arrangement of a set of objects

I'm currently working with an array of objects that I need to restructure into a new array. Despite my efforts, I haven't quite achieved the desired outcome.

The initial data I have is organized as follows:

data = Team > Days > Games

This data consists of sports teams and the games they are scheduled to play on each day from Monday to Sunday (0-6).

I require the data to be transformed into this structure:

data = Days > Teams > Games

Here's an example of the original data:

var data = [
    {
        id: 1,
        team: 'LA Lakers',
        days: [
            { id: 0, name: 'Monday', games: [{ id: 1, home: false }, { id: 2, home: true }, { id: 3, home: true }] },
            { id: 1, name: 'Tuesday', games: [] },
            { id: 2, name: 'Wednesday', games: [] },
            ...
        ]
    },
    {
        id: 2,
        team: 'NJ Nets',
        days: [
            { id: 0, name: 'Monday', games: [] },
            { id: 1, name: 'Tuesday', games: [] },
            { id: 2, name: 'Wednesday', games: [{ id: 1, home: false }, { id: 2, home: true }, { id: 3, home: true }] },
            ...
        ]
    },
];

Here is the format I aim to achieve:

var newData = [
    {
        id: 0,
        name: 'Monday',
        teams: [
            {
                id: 1,
                name: 'LA Lakers',
                games: [{ id: 1, home: false }, { id: 2, home: true }, { id: 3, home: true }]
            }
        ]
    },
    { id: 1, name: 'Tuesday', teams: [] },
    {
        id: 2,
        name: 'Wednesday',
        teams: [
            {
                id: 2,
                name: 'NJ Nets',
                games: [{ ... }, { ... }, { ... }]
            }
        ]
    },
    ...
];

I am considering using lodash and exploring the groupBy feature or potentially utilizing a for loop to populate a new array. Any suggestions or insights would be greatly appreciated.

Answer №1

using lodash 4.17.4 for my innovative approach

const result = _.chain(data)
    .flatMap('days')
    .uniqBy('id')
    .map(_.partialRight(_.omit, 'games')) // extracting days without games
    .map((day) => { // iterating through days
        // getting teams with games on this day
        const teamsWithGames = _.chain(data) 
            .filter(team => _.some(team.days, { id: day.id })) // filtering teams by day
            .map(_.partialRight(_.omit, 'days')) // removing days from teams
            .map((team) => {
                // assigning games on this day to the team 
                return _.chain(data)
                    .find({ id: team.id })
                    .get('days')
                    .filter({ id: day.id })
                    .flatMap('games')
                    .thru(games => _.assign({}, team, { games }))
                    .value();
            })
            .filter(team => _.size(team.games) > 0)
            .value();
       return _.assign({}, day, { teams: teamsWithGames }); // returning day with teams
    }, [])
    .value();

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

Creating an array of class objects

Can we initialize an array in the following manner? static const vec3d<long> XI[Q] = { vec3d<long>( 0, 0, 0 ), vec3d<long>(-1, 0, 0 ), vec3d<long>( 0,-1, 0 ), vec3d<long>( 0, 0,-1 ), vec3d<long>(-1,-1, 0 ), v ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

How can the dimensions of a gridhelper in three.js be adjusted?

Gridhelper only appears to have the ability to create a square grid based on size. Is there a way to make it generate a rectangular grid where I can specify both width and height in three.js? I am aware of the 'scale' property, but I'm conce ...

Tips for locating a specific value within an array using ReactJS

I have a set of dates provided by the back-end that I need to work with in order to perform a specific check. If the list contains dates from the month of March, I should display the events for March, and the same for April, and so on. My task involves se ...

stop the leakage of CSS and JS from the subtree to the document through the inverse shadow DOM mechanism

My page contains dynamic HTML content that I want to incorporate. The dynamic content consists of only HTML and CSS, without any JavaScript. However, I have some custom global CSS styles and JS logic that need to be implemented along with this dynamic con ...

What is the best method for displaying arrays in a specific format in PHP?

I have been working on a task to rearrange an array by reassigning every other value, with the following examples: 17.34502870451717,62.46137370987033 Resulting in this: 62.46137370987033,17.34502870451717 I have successfully achieved that part, but no ...

Having issues with loading THREE.js object within a Vue component

I'm baffled by the interaction between vue and THREE.js. I have the same object that works fine in a plain JS environment but not in vue.js. The canvas remains empty in vue.js and the developer console displays multiple warnings. The code I used in J ...

How to show an array in AngularJS and also display any selected values?

Can someone assist me in displaying a list of data from an array on the loading page? Additionally, I need help with showing the selected value from a dropdown once it is chosen. <!DOCTYPE html> <html> <head> <meta charset="utf-8"&g ...

Geometry of Rounded Corners Box - three.js

Although this question is primarily related to Math, I believe there may be alternative solutions available within threejs for my particular issue. My goal is to iterate through each vertex in a Box Geometry and determine whether it needs to be moved up o ...

Sending an attribute to the Treeselect Vue component from a Laravel view

I want to encapsulate Vue-Treeselect link: within its own custom vue component. This way, I can easily use something like <tree-select></tree-select> in a Laravel view file where needed. However, the challenge I'm facing is figuring out ...

How does Sizzle JS function?

While investigating the sizzle.js source code for a project, I stumbled upon an interesting discovery. Towards the end of the code, there is a line that reads: window.Sizzle = Sizzle; However, there doesn't seem to be any declaration of a variable n ...

Ambiguous limitation regarding noptr-new-declartor

Declaration of noptr-new-declarator: [ expression ] attribute-specifier-seq_opt noptr-new-declarator [ constant-expression ] attribute-specifier-seq_opt The reasoning behind using constant-expression in square brackets for the latter case of allow ...

How to prevent mouse click events in Three.js after interacting with an HTML overlay

Encountering an issue with Three.js: I have created my own HTML user interface as a simple overlay. However, I am facing a problem where the mouse click does not reset when I interact with elements on this overlay. Specifically, when I click on the "Came ...

Check if a Firestore document exists and display a button in Angular based on the boolean result

Seeking desired outcome: How to display a button in an Angular view based on the boolean value returned by an Angular Service that checks for the existence of a Firestore document. Current Scenario The Service successfully verifies the presence of t ...

The PHP bootstrap 4 Delete button is experiencing an issue with fetching the ID

I am facing an issue with the delete button and confirmation box feature that I have implemented. The problem seems to be related to transferring the id that I want to delete. Here is the table structure for the Delete button: <tbody> & ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

What is the reason why the VIEW SOURCE feature does not display filled dropdown list boxes?

The following code functions well in terms of dynamically populating two dropdown list boxes. Initially, the getBuildings function is called to make a request to the getBuildings.php file. This action fills the buildingID dropdown list box with options. ...

What steps should be taken to set up the datatable to sort records in descending order based on the creation date?

In my Rails application, I am utilizing the Datatable plugin to display data on the User index page. The first column in the index page is the created_at field, which displays dates like Mon, 17-Oct-16. I want to sort this column in descending order base ...

Encountering an issue with the autocomplete feature in the jQuery library where it is stating "this.source is not a function."

Here's the code snippet I'm working with: $.ajax({ type: "GET", url: "https://url.com", dataType: "json", success: function (data) { $("#search").autocomplete({ source: data, select: function (even ...

Is there a way to determine if the sum of certain elements in an array can equal K?

Consider a scenario where you have an arbitrary array with only positive values, such as A[5] = {2,3,4,2}. Let's say you want to determine if a given int x, for example x=2, can be represented as the sum of other elements in the array. In this case, T ...