Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I would like to tackle this problem using plain JavaScript.

let commandList = [
                 {
                    id_commande: 18,
                    date: "2020-12-07",
                    etat: "en traitement",
                    nom: "Tom Kha Gai",
                    prix_total: 16.68,
                    quantite: 1,
                },
                {
                    id_commande: 18,
                    date: "2020-12-07",
                    etat: "en traitement",
                    nom: "Tom Yum Talai",
                    prix_total: 16.68,
                    quantite: 1,
                },
                {
                    id_commande: 19,
                    date: "2020-12-07",
                    etat: "en traitement",
                    nom: "Tom Yum Gai",
                    prix_total: 16.1,
                    quantite: 1,
                },
                {
                    id_commande: 19,
                    date: "2020-12-07",
                    etat: "en traitement",
                    nom: "Tom Yum Tai",
                    prix_total: 16.1,
                    quantite: 1,
                }
            ];

The desired output is :

let combined = [{
                        id_commande: 18,
                        date: "2020-12-07",
                        etat: "en traitement",
                        plats: [{
                                nom: "Tom Kha Gai",
                                quantite: 1
                            },
                            {
                                nom: "Tom Yum Talai",
                                quantite: 1
                            }
                        ],
                        prix_total: 16.68
                    },
                    {
                        id_commande: 19,
                        date: "2020-12-07",
                        etat: "en traitement",
                        plats: [{
                                nom: "Tom Yum Gai",
                                quantite: 1
                            },
                            {
                                nom: "Tom Yum Tai",
                                quantite: 1
                            }
                        ],
                        prix_total: 16.1
                    },
                ]

Answer №1

If you want to effectively manage this data, consider using the reduce method.

let orderList = [
    {
        order_id: 18,
        date: "2020-12-07",
        status: "processing",
        name: "Tom Kha Gai",
        total_price: 16.68,
        quantity: 1,
    },
    {
        order_id: 18,
        date: "2020-12-07",
        status: "processing",
        name: "Tom Yum Talai",
        total_price: 16.68,
        quantity: 1,
    },
    {
        order_id: 19,
        date: "2020-12-07",
        status: "processing",
        name: "Tom Yum Gai",
        total_price: 16.1,
        quantity: 1,
    },
    {
        order_id: 19,
        date: "2020-12-07",
        status: "processing",
        name: "Tom Yum Tai",
        total_price: 16.1,
        quantity: 1,
    }
];

const result = orderList.reduce((res, current) => {
    const existingOrder = res.find(e => e.order_id === current.order_id);
    if (existingOrder) {
        existingOrder.items = [...existingOrder.items, { name: current.name, quantity: current.quantity }]
        return res
    } else {
        return [...res, {
            order_id: current.order_id,
            date: current.date,
            status: current.status,
            items: [{
                name: current.name,
                quantity: current.quantity
            }],
            total_price: current.total_price
        }]
    }
}, [])

console.log(result)

Answer №2

give this a shot:

var orderList = [
                 {
                    order_id: 18,
                    date: "2020-12-07",
                    status: "processing",
                    item: "Tom Kha Gai",
                    total_price: 16.68,
                    quantity: 1,
                },
                {
                    order_id: 18,
                    date: "2020-12-07",
                    status: "processing",
                    item: "Tom Yum Talai",
                    total_price: 16.68,
                    quantity: 1,
                },
                {
                    order_id: 19,
                    date: "2020-12-07",
                    status: "processing",
                    item: "Tom Yum Gai",
                    total_price: 16.1,
                    quantity: 1,
                },
                {
                    order_id: 19,
                    date: "2020-12-07",
                    status: "processing",
                    item: "Tom Yum Tai",
                    total_price: 16.1,
                    quantity: 1,
                }
            ];
        groupedOrders = function (orderList) {
        var result = [];
        orderList.forEach(function (a) {
            var key = a.order_id + '|' + a.date+ '|' + a.status;
            if (!this[key]) {
                this[key] = { order_id: a.order_id, date: a.date, status: a.status, items: [] };
                result.push(this[key]);
            }
            this[key].items.push({name : a.item, quantity : a.quantity});

        }, {});
        return result;
    }(orderList);    
           
           document.write('<pre>' + JSON.stringify(groupedOrders, 0, 4) + '</pre>');

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

Mastering the art of grouping by a key and generating sub-objects from a plain array of key-value pairs in JavaScript ES5 without relying on third-party libraries

My dataset consists of an array of objects, each containing 4 keys: [ { "team": "USA", "team_profile_id": "10", "player": "Captain America", "player_id": "10X1" }, { "team": "USA", "team_profile_id": "10", "player": "The ...

Encountering a npm script error while running on a Windows operating

While using webpack to build my application, I encountered the following error message in the command prompt: [email protected] dev D:\Myprograms\java script\forkify webpack --mode development The error mentioned: Insufficient num ...

Securing Codeigniter with CSRF protection while using datatables and an AJAX URL

I am currently utilizing codeigniter and have implemented CSRF protection. We have enabled it using the following configuration: $config['csrf_protection'] = TRUE; For form submission, we are using the following code: `<input type="hidden" ...

Creating a custom jQuery selector

I've been struggling with a particular problem all day today, trying different approaches but still unable to find a solution. The crux of the issue is this: I have multiple JavaScript functions running to determine whether certain variables should b ...

Obtain the range of values for a match from an array using Vue.js

I have an array in my Vue.js code with values 25, 100, 250, and 500. I am looking to find the key value that matches a specific range. For example, if the input is 5, then the output should be 25. However, the code I tried returns all values within the ran ...

Adjust the text color based on the background image or color

Here on this site, I have designed the first div to display a dark image, while the second one shows a light background. I am aiming to adjust the sidebar text color based on whether it is displayed against the dark or light background. How can I achieve ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

What is the quickest and most effortless method for accessing the API using developer tools?

What is the quickest and easiest way to access the API using developer tools? I need a clear and concise explanation on how to quickly navigate to this interface I want to handle this task through developer tools ...

ReactJS integration issue with Material Design Lite (import/require problem)

I am currently integrating Google's Material Design Lite with ReactJS. Specifically, I am utilizing the Spinner Loading and Text Field components from the MDL library. However, I am encountering an issue when switching routes using React Router. The ...

Change the color of this element and input field background

Having trouble with setting the background color of an input field to red in this code: $(document).ready(function(){ $(".abc").focus(function(){ $(this).attr('background', 'red'); $("label").text('Insert tex ...

Why are JS & jQuery's inArray() and indexOf() functions not functioning correctly when indexes are strings?

Here is an example of an array: var arr = []; arr['A string'] = '123'; arr['Another string'] = '456'; I am attempting to find the index of either '123' or '456'. Both methods below are returnin ...

Determine the Height of the Container once the Font File has Finished Loading

When styling a website with a unique font using @font-face, the browser must download the font file before it can display the text correctly, similar to how it downloads CSS and JavaScript files. This poses an issue in Chrome (v16.0.912.63) and Safari (v5 ...

JavaScript code to shift a box beyond the boundaries of a grid

I have a yellow square within a grid. Upon clicking the 'UP' button, the yellow square moves up by one box. How can I ensure that the square stops at the edge of the grid and does not move out? let moveCounter = 0; var grid = document.getElem ...

jQuery's visibility check function is not functioning properly

I am developing a web application for managing orders and finance in a restaurant. To enhance the functionality of my application, I require more screens to operate with. To facilitate this, I have implemented a small function to toggle between visibility: ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Utilize the scrollIntoView method within a jQuery function

My current setup involves using JQuery's show and hide function. Essentially, when an image is clicked, it triggers the display of an information log. The issue I am facing is that this log opens at the top of the page, whereas I would like it to scro ...

What is the process for changing the output paper size to A4 in React Native (expo android)?

Using React Native to develop an Android app for billing purposes, I encountered an issue with the output paper size being 216mmX279mm instead of the standard PDF size of 210mmX297mm. Utilizing expo-print and printToFileAsync from expo, I aim to achieve a ...

What is the process of emphasizing a WebElement in WebdriverIO?

Is there a way to highlight web elements that need to be interacted with or asserted in webdriverIO? Or is there a JavaScript code similar to the javascript executor in Selenium that can be used for this purpose? ...

Determining the total number of combinations possible from a collection of five arrays containing items

I have five massive collections filled with various strings, and each of them contains a different number of elements. Below are examples of the lists: List 1 "Jeffrey the Great", "Bean-man", "Joe", "Charles", "Flamur", "Leka", ...

Potential Scope Problem in Angular JS Controller

The HTML code snippet I have is as follows: <body ng-controller = "Control as control"> <button ng-click = "control.prepareAction()">Do Action </button> <div id="one" ng-hide = "!control.showOne" > <div> <h6> ...