KeyBy lodash method stores values in an object using the specified property as keys

There are multiple items stored in an array:

"objects": [
    {
        "category": "XXXXX",
        "item_name": "over_pkg_0",
        "price": 230
    },
    {
        "category": "XXXXX",
        "item_name": "over_pkg_1",
        "price": 54
    },
    {
        "category": "YYYYY",
        "item_name": "over_pkg_0",
        "price": 25
    },
    {
        "category": "YYYYY",
        "item_name": "over_pkg_1",
        "price": 25
    }
];

My goal is to reorganize the data using lodash as follows:

"objects": [
    {
        "XXXXX": [
            {
                "name": "over_pkg_0",
                "amount": 230
            },
            {
                "name": "over_pkg_1",
                "amount": 54
            }
        ],
    },
    {
        "YYYYY": [
            {
                "name": "over_pkg_0",
                "amount": 25
            },
            {
                "name": "over_pkg_1",
                "amount": 25
            }
        ],
    }
];

I have made some attempts, but I can't seem to separate the keys and convert them into arrays. Perhaps utilizing _.concat could provide a solution, but I haven't been able to implement it successfully.

I tried using:

var revisedObjects = _.chain(objects)
  .keyBy('category')
  .mapValues(v => _.omit(v, 'category'))
  .value();

This code results in:

"revisedObjects": {
    "XXXXX": {
        "name": "over_pkg_1",
        "amount": 54
    },
    "YYYYY": {
        "name": "over_pkg_1",
        "amount": 25
    }
}

Answer №1

Utilize _.groupBy() function to categorize an array of objects based on a specific key:

const data = { surcharges: [{"supplier":"XXXXX","name":"over_pkg_0","amount":230},{"supplier":"XXXXX","name":"over_pkg_1","amount":54},{"supplier":"YYYYY","name":"over_pkg_0","amount":25},{"supplier":"YYYYY","name":"over_pkg_1","amount":25}]};

const finalsurcharges = _(data.surcharges)
    .groupBy('supplier')
    .mapValues((g) => g.map(o => _.omit(o, 'supplier')))
    .value();

console.log(finalsurcharges);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

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

How can I make my div change color when the check-box is selected?

I have a dynamic table in my web application that is populated with data from a database. Each row in the table represents multiple time slots for a specific date. I am working on a feature where the background color of a time block can be changed if a che ...

The nullish coalescing operator in JavaScript is running code on both of its sides

console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist'); console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exis ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Unsure of the best way to approach pagination using {$.getJSON, php image array} - seeking guidance on the right

Currently, my code is set up as follows: When a user visits a specific link on the page The $.getJSON function sends a request to a PHP script PHP uses scandir() to generate an array containing image names (eventually in the hundreds to thousands, ...

Progressive reloading page with Jquery Ajax upload

I've encountered a strange issue with a Jquery form submit. After the upload completes, the page reloads even though the server hasn't finished processing. The server only returns a JSON success status, so it's not an issue on the server s ...

Error message: "Unable to find a windows instance" encountered while conducting tests on Paho MQTT Client using mocha and typescript

After spending countless days searching online, I have yet to find any resources on testing the Paho MQTT Client. My approach so far has been somewhat naive, as shown below: import { suite, test, slow, timeout, skip, only } from 'mocha-typescript&apo ...

Queue with promises

My challenge is to process an array of files, in batches of N. I have a function called doWork that returns promises. var files = [] var doWork = function(file) { return asyncFn(file) } I want the ability to dynamically add items to this queue. Updat ...

Malformed JSON request format detected

My request DTO was created using beans.xml and it included the @JsonPropertyOrder and @JsonProperty annotations as shown below in the beans.xml file: <bean ...> <annotations>@JsonPropertyOrder({ "FirstName", "LastName" ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

What steps are involved in integrating Element Plus with Nuxt 3?

Seeking assistance with installing Element Plus in Nuxt 3. I followed the instructions from the official Element Plus documentation, but despite adding unplugin-vue-components, unplugin-auto-import, and adjusting webpack settings in the nuxt config file, ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

data being returned twice onpopstate

After experimenting with onpopstate, I encountered an issue. When I click the back button in my browser, the URL changes as expected, but the page code loads twice, resulting in duplicate lists and div elements. Why is this happening and how can it be reso ...

How to Determine If a String Represents an HTML Tag Using jQuery

Checking if a string is an HTML tag can be tricky. I've tried various methods found on Google, but none have been successful so far: var v = $(string).html() ? 1 : 0; --or---------------------------------------------- var htmlExpr = new RegExp("/^( ...

Firefox does not allow contenteditable elements to be edited if they are nested inside a parent element that is draggable

Here is a basic HTML example: <div draggable=true> <div contenteditable=true>can't edit me</div> </div> When testing in Chrome, I noticed that I was able to edit the contents of the contenteditable div, however, this functi ...

Issue with OnChange event in HTML and Adding Content with Jquery

I'm currently working on an app that includes a dynamic dropdown feature using jQuery and the append() method to display changing numbers dynamically. Everything seems to be functioning well in the first field of the form, but when I try to add more f ...

Vue router is designed to maintain the state of child components without requiring them to

Encountering a strange problem with vue-router. Developed a simple CRUD app for managing users. The app includes four main views: User list and a create button Create view with a form child component that fetches field data from an API within the creat ...

Eliminate the presence of core-js in the nextjs bundle

Currently, I am tackling the challenge of minimizing bundle sizes in my Next.js project. One particular aspect that caught my attention is the inclusion of a core-js bundle for polyfills. This adds an extra 50KB to the size of the main bundle, which I aim ...

Modifying the cursor presentation in the Atom editor

Hey there, I'm curious if there is a method to customize the caret style in Atom similar to how it's done in Sublime Text 3. In Sublime Text 3, you can change the caret style using this JSON setting: "caret_style": "phase" Is there a comparable ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...