Organizing elements in JavaScript

By utilizing d3.nest, I've organized this list through element grouping from another list.

array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3},
                               {Id: "1234b", ECTS: 3}]}, 
          {key: "7S", values: [{Id: "1534a", ECTS: 5},
                               {Id: "154b", ECTS: 4},]} ]

The goal is to transform the current format into something like this:

array = [{key: "6S", values: { 3: [{Id: "1234a"}, {Id: "1234b"}]}},

        {key: "7S", values: { 5: [{Id: "1534a"}], 4: [{Id:"1534a"}]}}]

Specifically, I aim to group the data for each key (e.g. 6S, 7S) based on their ECTS values. Despite attempts with _.groupBy method, I encountered difficulties due to the objects being already grouped once. Any suggestions on how to effectively group these items?

Answer №1

If you're looking for a solution, consider the example code snippet below:

var array = [ {key: "6S", values: [{Id: "1234a", ECTS: 3}, {Id: "1234b", ECTS: 3}]},  {key: "7S", values: [{Id: "1534a", ECTS: 5}, {Id: "154b", ECTS: 4},]} ];


array.forEach((obj) => {
    var values = {};
    
    obj.values.forEach((item) => {
       values[item.ECTS] = values[item.ECTS] || [];
       values[item.ECTS].push({"Id": item.Id});
    });
    
    obj.values = values;

});
                  
console.log(array);

Answer №2

const studentData = [{
        course: "6S",
        info: [{
                Id: "1234a",
                ECTS: 3
            },
            {
                Id: "1234b",
                ECTS: 3
            }
        ]
    },

    {
        course: "7S",
        info: [{
                Id: "1534a",
                ECTS: 5
            },
            {
                Id: "154b",
                ECTS: 4
            },
        ]
    }
]

const updatedStudentData = studentData.map(function(item) {
    var updatedInfo = item.info.reduce(function(obj, data) {
        obj[data.ECTS] = obj[data.ECTS] || [];
        obj[data.ECTS].push({
            Id: data.Id
        });
        return obj;
    }, {});
    item.info = updatedInfo;
    return item;
});

console.log(updatedStudentData);

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

Struggling to integrate a JavaScript sdk with an Angular2 application due to missing dependencies

I've been struggling to incorporate the Magic: The Gathering SDK library into my Angular2 application. I've tried various methods, but nothing seems to work seamlessly. When I attempt to import the library using TypeScript like this: import { } ...

Revamp responsiveness in bootstrap 3 for printing with @media queries

My goal is to disable the responsive features of bootstrap when the event javascript:print() is triggered. This way, I want my webpage to maintain the column grid layout that I have defined, regardless of screen size. One solution suggested in this answer ...

What is the best way to display table rows for a specified date range?

I am working with a table and need to display only the rows that fall between two specific dates. <table id ="Table"> <thead> <tr> <th>Date</th> <th>Name</th> <th>Desc</th> </tr> </thead> ...

How to troubleshoot the error I am encountering in Vue while using custom HTML tags?

While I'm still a Vue newbie, I find it quite enjoyable. I've been experimenting with using just a custom tag like this: <ui-button>Learn more</ui-button> Unfortunately, I encountered an error asking me to register the component. To ...

Retrieve image data by capturing the image from the input field and showing it on the screen

I've been searching online and can't seem to find a clear answer on whether this task is possible. Here's what I want to achieve before submission: When a user chooses a file for upload, I aim to extract the image data and convert it into b ...

React: Remember to always retain the initial four characters when making changes

I have implemented an input component for phone numbers using the react native phone input library, which automatically adds the international code. However, I am facing an issue where the international code +234 is deleted when the user presses the back b ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

Tips for building a geometric shape using an array in JavaScript and Three.js

What is the most efficient method for transforming this data array into a geometry? I am generating the array dynamically and have the option to create an object instead of an array. Any suggestions for improving this process would be greatly appreciated. ...

Passing Selectize.js load callback to a custom function

I set up selectize.js to gather configuration options from html data attributes. One of the configurations involves specifying a js function for custom data loading (not just simple ajax loading). Everything was working smoothly until I tried running an as ...

Evaluating the similarity between a Guild ID and a matching string

Currently, I am in the process of creating a bot with a unique feature - a config command that enables users to customize specific functionalities within their servers. This customization is facilitated through a straightforward JSON file named config.json ...

When using Rspec and Capybara, utilizing jQuery to set focus on an element may not apply the `:focus` CSS as expected

I have implemented jump links for blind and keyboard users on my website, but I've hidden them off-screen visually. When these links gain focus, they are moved into the viewport. Trying to test this behavior using RSpec and Capybara has been unsucces ...

What are the steps to transition from @zeit/next-sass deprecation?

Is there a way to transition and modify the next.config.js file to switch from using @zeit/next-sass to leveraging Next.js's built-in support for Sass? Check out this link for more information: https://www.npmjs.com/package/@zeit/next-sass const withS ...

Ways to divide a cluster in three.js?

My dilemma involves voxels that require grouping, so I have opted to place them in a container: container.add(e); Next, I integrate the container into the scene. However, I am now faced with the challenge of how to separate the voxels without the need to ...

Tips for aligning an image in the middle of a column within an ExtJS GridPanel

My goal is to center the icon horizontally within the "Data" column: Currently, I have applied textAlign: center to the column: Additionally, I am using CSS in the icon renderer function to horizontally center it: Despite these efforts, the icon remains ...

Next.js allows for dynamic page routing using the `useState` hook to redirect users

In my Next.js project, I am using the useState hook to render different components based on the button a user clicks. The main page, called account.js in the application, contains the following code: // Importing react and getting components import React f ...

Is there a method to detect the presence of a bot in your discord server using another bot?

I am developing my own unique discord bot and I am looking to implement a feature that can determine if a specific bot is present in the server. Here's how I've been approaching it: if (!message.guild.args[0]) In this code, args[0] represents ...

Arrange the child elements of a div to be displayed on top of one another in an HTML document

I am struggling with a div containing code .popupClass { width: 632px; height: 210px; position: absolute; bottom:0; margin-bottom: 60px; } <div class="popupClass"> <div style="margin-left: 90px; width: 184px; hei ...

What are some effective ways to test asynchronous functions in React?

Looking for help to test async/Promise based methods in React components. Here is a simple example of a React component with async methods: import server from './server'; class Button extends Component { async handleClick() { if (await ca ...