Exploring the concept of grouping arrays in JavaScript

Hey there! I'm new to JavaScript and currently using the Knex ORM for database interactions. I'm facing an issue where I am getting flat JSON as a result from my queries, but I need it in a different format as mentioned in the expected results section. I've tried some code snippets, but none of them are giving me the desired output. I've included my prototype code below along with the resulting output, which is not what I want. How can I achieve the actual result using lodash or ES6 higher order functions?

var data= [
    {order_id: 1,kot_id: 10,price: 20,quantity: 2},
    {order_id: 1,kot_id: 10,price: 100,quantity: 1},
    {order_id: 1,kot_id: 10,price: 150,quantity: 1},
    {order_id: 1,kot_id: 11,price: 55,quantity: 1},
    {order_id: 1,kot_id: 11,price: 250,quantity: 3},
]

let objects = {}
let arr = []
result = data.forEach((item,index) => {
    if(!objects.order_id) {
        objects = {order_id: item.order_id,list: []}
        arr.push(objects)
    }
    if(!objects.kot_id) {
         objects.list.push({kot_id: item.kot_id,kot_list: []})

    }
    objects.list[index].kot_list.push({price: item.price,quantity: item.quantity})

})
console.log(JSON.stringify(arr,null,2))

RESULT OF THE ABOVE CODE
[

  {
    "order_id": 1,
    "list": [
      {
        "kot_id": 10,
        "kot_list": [
          {
            "price": 20,
            "quantity": 2
          }
        ]
      },
      {
        "kot_id": 10,
        "kot_list": [
          {
            "price": 100,
            "quantity": 1
          }
        ]
      },
      {
        "kot_id": 10,
        "kot_list": [
          {
            "price": 150,
            "quantity": 1
          }
        ]
      },
      {
        "kot_id": 11,
        "kot_list": [
          {
            "price": 55,
            "quantity": 1
          }
        ]
      },
      {
        "kot_id": 11,
        "kot_list": [
          {
            "price": 250,
            "quantity": 3
          },

        ]
      }
    ]
  }
]

EXPECTED RESULT

result = [
    {
        order_id: 1,
        list: [
            {
                kot_id: 10,
                kot_list : [
                    { price: 200,quantity: 2 },
                    {price: 100,quantity: 1},
                    {price: 150,quantity: 1}
                ]
            },
            {
                kot_id: 11,
                kot_list: [
                    {price: 55,quantity: 1},
                    {price: 250,quantity: 3}
                ]
            }
        ]
    }
]

Answer №1

lodash has some great functions like groupBy and mapValues that can simplify the task at hand.

Lodash provides a concise way to achieve the desired outcome:

const data = [
    {order_id: 1, kot_id: 10, price: 20, quantity: 2},
    {order_id: 1, kot_id: 10, price: 100, quantity: 1},
    {order_id: 1, kot_id: 10, price: 150, quantity: 1},
    {order_id: 1, kot_id: 11, price: 55, quantity: 1},
    {order_id: 1, kot_id: 11, price: 250, quantity: 3},

    {order_id: 2, kot_id: 10, price: 150, quantity: 1},
    {order_id: 2, kot_id: 11, price: 55, quantity: 1},
    {order_id: 2, kot_id: 11, price: 250, quantity: 3},
]


const result = _(data)
  .groupBy('order_id')
  .mapValues((values, key) => {
    return _(values)
      .groupBy('kot_id')
      .map((list, id) => ({
        kot_id: id,
        kot_list: _.map(list, i => _.pick(i, ['price', 'quantity']))
      }))
      .value();
  })
  .map((list, order_id) => ({order_id, list}))
  .value();


console.log(JSON.stringify(result, null, 4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Alternatively, you can opt for ES6 methods to accomplish a similar outcome:

Here's an example using plain ES6 syntax:

const data = [
    {order_id: 1, kot_id: 10, price: 20, quantity: 2},
    {order_id: 1, kot_id: 10, price: 100, quantity: 1},
    {order_id: 1, kot_id: 10, price: 150, quantity: 1},
    {order_id: 1, kot_id: 11, price: 55, quantity: 1},
    {order_id: 1, kot_id: 11, price: 250, quantity: 3},

    {order_id: 2, kot_id: 10, price: 150, quantity: 1},
    {order_id: 2, kot_id: 11, price: 55, quantity: 1},
    {order_id: 2, kot_id: 11, price: 250, quantity: 3},
]


const orderIds = [...new Set(data.map(i => i.order_id))];
const kotIds = [... new Set(data.map(i => i.kot_id))];

const result = orderIds.map(order_id => {
  return {
    order_id,
    list: kotIds
      .map(kot_id => {
        return {
          kot_id,
          kot_list: data
            .filter(i => i.order_id === order_id && i.kot_id === kot_id)
            .map(i => ({price: i.price, quantity: i.quantity}))
        }
      })
  };
});

console.log(JSON.stringify(result, null, 4));

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

Mandate distinct fields when storing embedded records

device.rb class Device include Mongoid::Document field :devui, type: String field :name, type: String belongs_to :user embeds_many :responses When fetching data from an external server, a JSON with an id field is obtained. When trying to insert ...

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...

Tips on saving an array of objects in MongoDB using Mongoose

I am struggling to save complex data, such as an array of objects, in mongoose. Despite trying a few different approaches, I have been unsuccessful in saving the data. My schema is defined as shown below, and I need to save an array of objects that can po ...

Insert multiple text box values as a new entry in an SQL database

Currently, I am implementing a code snippet to incorporate additional text boxes within a form. The main purpose is to enable users to input multiple languages they are proficient in. <script> jQuery(function($) { var i = 0; ...

Can changes made through JavaScript in Selenium affect the driver's page source?

After clicking on a button that triggers a JavaScript function to update the page by adding new HTML elements, I checked the driver.page_source but couldn't see any changes. How can I retrieve the HTML generated by this JavaScript function? ...

Issues with using the $and operator in MongoDB with Mongoose not producing desired outcomes

modelThreader.find({ $and: [ {"date_entered": { $lt: fromTime }}, {"cancelled": { $ne: true }}, {"hideFromUserIds.id": { $ne: current_user_id }}, {"banned": false}, {$and: [ ...

Submitting buttons by using a textbox array is a simple process

I need help figuring out why my buttons are not working on a page I'm creating with around 300 textboxes generated from a foreach loop. While I've successfully been able to write links into the textboxes, I am struggling to read the textboxes arr ...

Exploring the depths of JSON nested maps in Groovy: a step-by-step guide

I have received the following JSON output from AWS DynamoDB and I am looking to loop through it in order to populate a table within Jenkins Parameters using a Groovy script. Is this achievable? JSON: [ { "test": { "S ...

Steps to resolve the error message 'ReferenceError: hello is not defined' in your code

I'm currently working on a game development project, aiming to create a mining-themed game. One of the core features I'm implementing involves clicking a button to increase a numeric value. In my game setup, players click to collect ores, and the ...

Transforming single-to-multiple json files into a csv format

I'm currently facing a challenge in parsing the json output from an API call. The returned data consists of an array of orders, each containing an array of items. My goal is to parse this information in order to generate a single CSV file that include ...

How to convert a nested array of objects into a string using JavaScript for passing as a URL parameter

So, I'm dealing with a nested JSON array of objects here. My goal is to pass it as a parameter in the URL and then save it to my MongoDB database. However, when I tried doing that, it ended up being saved as [object object]. Does anyone know how to so ...

Angular Material Table encounters issues with Pagination, Sorting, and Filtering when handling large JSON dataset

I have been encountering an issue where I am attempting to transmit JSON data with over 50,000 entries from an express server to Angular. While the deployment displays all the entries in an Angular Material table format, the features such as pagination, so ...

Create a captivating sliding effect on Windows 8 using a combination of CSS and JavaScript

I believe that using css3 alone can achieve this effect, but I'm struggling with understanding properties like 'ease' in css3. This is the progress I have made so far: http://jsfiddle.net/kwgy9/1/ The word 'nike' should slide to ...

Interacting with jQuery mouse events on elements below the dragged image

I'm attempting to create a drag-and-drop feature for images using jQuery. While dragging, I generate a thumbnail image that follows the mouse cursor. However, this is causing issues with detecting mouseenter and mouseleave events on the drop target pa ...

Error in Angular: IE8 is expecting an identifier

My application runs smoothly on most browsers, but I encounter an issue with IE8 where an Expected Identifier error occurs. $scope.delete = function (index) { $scope.recipelists.splice(index, 1); localStorage.setItem('markedRecipes ...

Is there a way to access the versionCode of an app that is not mine?

I am trying to implement a function that will compare the versionCode of an external app stored in a json file on my server with the versionCode of another app. If the versionCode in the json file is greater than the one in the other app, I want to trigger ...

Performing two ajax calls within a non-existent div that has only just been appended

I've been developing a website similar to 9gag. I attempted to incorporate a voting feature created by someone else, as I'm not well-versed in AJAX requests, but it just doesn't seem to be functioning. My index.php file fetches five posts f ...

Executing a for loop with a parameter passed into the setTimeout function

Help Needed with AJAX Request Timeout Issue I recently created an array and tried to send an ajax request using setTimeout. However, I encountered a problem where I couldn't get the parameter in setTimeout. The console log showed that the variable &a ...

Error: No route found at this location

I've been following a tutorial on integrating Evernote with IBM's DOORS Next Generation and I added the code highlighted below. // app.js app.get("/notebooks", function(req, res) { var client = new Evernote.Client({ token: req.session.oauth ...