Converting a collection of objects in Javascript

Is there a more efficient way to transform an array of objects with JavaScript? I'm new to working with JavaScript and struggling to achieve the desired formatted array. Any help would be greatly appreciated, thank you.

This is what I've attempted...

// Trying to get the formatted reports array
        $scope.reports = [];
        var num = 1;
        
        for(var i=0; i<$scope.reports_data.length; i++) {
            var row = {
                "reviewer_1" : "",
                "reviewer_2" : "",
                "reviewer_3" : "",
                "created_at" : ""
            };
            if(num == $scope.reports_data[i].report_id) {
                row.created_at = $scope.reports_data[i].created_at;
                if($scope.reports_data[i].stage == 1 ) {
                    row.reviewer_1 = $scope.reports_data[i].full_name;
                } else if($scope.reports_data[i].stage == 2) {
                    row.reviewer_2 = $scope.reports_data[i].full_name;
                } else {
                    row.reviewer_3 = $scope.reports_data[i].full_name;
                }
            }
            $scope.reports.push(row);
            num += 1;
        }

Before:

    var raw_arr = [
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"Dick",
        "report_id" : 1,
        "stage" : 1
    },
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"Tom",
        "report_id" : 1,
        "stage" : 2
    },
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"Harry",
        "report_id" : 1,
        "stage" : 3
    },
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"John",
        "report_id" : 2,
        "stage" : 1
    },
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"Mike",
        "report_id" : 2,
        "stage" : 2
    },
    {
        "created_at" :"2016-05-04T16:45:07.000Z",
        "full_name" :"Charles",
        "report_id" : 2,
        "stage" : 3
    }
];

After:

 var formatted_arr = [
        {
            "created_at": "2016-05-04T16:45:07.000Z",
            "report_id": 1,
            "reviewer_1": "Dick",
            "reviewer_2": "Tom",
            "reviewer_3": "Harry",
        },
        {
            "created_at": "2016-05-04T16:45:07.000Z",
            "report_id": 2,
            "reviewer_1": "John",
            "reviewer_2": "Mike",
            "reviewer_3": "Charles",
        }
    ];

Answer №1

Utilize the power of Array.reduce in this situation. Instead of converting to an object with id keys, you can directly utilize the numeric keys as an array:

var raw_arr = [
    {
        "created_at": "2016-05-04T16:45:07.000Z",
        "full_name": "Dick",
        "report_id": 1,
        "stage": 1
    },
    {
        "created_at": "2016-05-04T16:45:07.000Z",
        "full_name": "Tom",
        "report_id": 1,
        "stage": 2
    },
    // more data follows...
];

var outputArr = raw_arr.reduce(function(p,c) {
    if (!p[c.report_id - 1]) {
        p[c.report_id - 1] = { 
            created_at: c.created_at,
            report_id: c.report_id
        }
    }
    p[c.report_id - 1]["reviewer_" + c.stage] = c.full_name;
    return p;
}, []);

console.log(JSON.stringify(outputArr));

The crucial code snippet is as follows:

var outputArr = raw_arr.reduce(function(p,c) {
    if (!p[c.report_id - 1]) {
        p[c.report_id - 1] = { 
            created_at: c.created_at,
            report_id: c.report_id
        }
    }
    p[c.report_id - 1]["reviewer_" + c.stage] = c.full_name;
    return p;
}, []);

Answer №2

const groupByReportId = _.groupBy(array, 'report_id');
_.map(grouped, function(data) {
    var output = data[0];
    delete output.full_name;
    delete output.stage;
    _.map(data, function(entry, index) {
        output['reviewer_' + (index + 1)] = entry.full_name;
    });
    return output;
});

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

The exceljs excel sheet in nodejs is not populating with all the necessary data

In my report task, I need to create an excel file with all the data and then send it to customers via email from the backend. I have successfully used excel.js to write the excel file, but I'm facing issues when dealing with large amounts of data (200 ...

Using HTML or JavaScript to generate a multitude of identical HTML elements on a webpage

I am currently designing a page that requires the presence of numerous tree illustrations with leaves, spanning across the width at the bottom of the page. I have considered two methods to achieve this. One option is to create a single set of trees and lea ...

Optimal approach for incorporating AJAX/jQuery functionality to both append to a form and refresh a list simultaneously on a single webpage

Currently, I am developing a page that consists of a form to input data into a table, as well as a list displaying items from that table. My goal is to ensure that the newest items appear at the top of the list after the form submission. At the moment, t ...

Building a hierarchical JSON structure from a string hierarchy

These 4 variables represent different players and their teams: var player1 = {name:'ronaldo', team: 'europe/spain/realmadrid'} var player2 = {name:'messi', team: 'europe/spain/barcelona'} var player3 = {name:'g ...

Prisma DB is a versatile database that excels in handling m-n

In my database, I have implemented a structure with 3 tables: Member, Characters, and MemberCharacters. Each member can have multiple Characters, and each Character can be used by multiple Members. To handle this many-to-many relationship, I have utilized ...

Manipulating URL parameters in Angular 2

I have implemented the following code: this.router.navigate(['/app/chart', {chartColor: this.color, chartWidth: this.width}]); Upon executing this code, the URL is set to: http://localhost/app/chart;chartColor=blue;chartWidth=600 Everything s ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

Is there a way to eliminate a square bracket and effectively obtain JSON in a nodejs/websocket environment?

Currently, I am able to retrieve data for a specific key (index) using console.log(auction[index].id);, but what I really need is to access the data directly with console.log(auction.id);. How can I achieve this? I am working with nodejs, and my WebSocket ...

10, 9, 8... Preparing to forward you to the next page

Hello there, I am currently working on a webpage that has a 10 second delay before redirecting. var timer = window.setTimeout('redirect(strUrl)', 11000); The function redirect(strUrl) simply changes the document's location. I think it w ...

Is there a way to quickly convert a deconstructed object into a specific type with just one

const { myFunc } = param[0].execute; Is there a way to convert myFunc to a string? This approach is ineffective const { myFunc } = param[0].execute as string; ...

A frigid commitment sealed within a software test

I've encountered an unexpected issue while testing a service that returns a standard $q promise. Strangely, none of the promises I test seem to be resolved or rejected (specifically, the handlers from then are not being called even though the code ins ...

Creating JavaScript objects using dynamic methods

I am currently working on creating a data object structure that resembles the following: let data = [{"label":"Category A", "value":20}, {"label":"Category B", "value":50}, {"label":"Category C", "value":30}]; Thus far, I ha ...

Dealing with notifications using setInterval

I am currently working on creating a Facebook-style notification using setInterval. The notification is functioning correctly, but the issue I am facing is that the div containing the notification closes every 6 seconds. I suspect the root cause is the set ...

Data not showing up in res.render

I've developed a function that organizes email addresses in various formats and validates them. While everything is functioning correctly on the server-side, I'm encountering difficulties trying to showcase the results within my Jade template. De ...

PHP retrieve rows with matching first words - must be exact matches

$companies = array( array('id' => '1','name' => 'Fifo Limited'), array('id' => '2','name' => 'FIFO Ltd'), array('id' => '3','name& ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

Executing functions within express - a mystery

I am struggling with a back-end JavaScript issue in Express. For some reason, when I call my function, it is returning undefined. Here's how it looks: // express route structure: exports.check = function(req, res) { // check if the username is prese ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

On click, triggering the class "animate__animated animate__bounce" to activate

Just starting to learn html and css and came across this awesome library: Here's the code snippet I have so far: <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.mi ...

Utilizing aliases for importing modules in Cypress using ES6 syntax

Within my current project, I am utilizing cypress alongside plain JavaScript. The main challenge I am encountering is the need to import modules (page objects) using aliases instead of resorting to spaghetti code like ../../../../folder/page.js. I do not i ...