How to efficiently group all keys in lodash using groupBy

I'm currently exploring ways to efficiently aggregate all items within a collection.

Specifically, I am interested in identifying the most effective method using Lodash to group this set of objects by each of their keys (in depth), assuming that the values are neither sub-objects nor arrays.

let input = [{
    food: {
        fruits: {
            apples: 2,
            bananas: 3,
            peaches: 'square',
            citrus: [100,200,300] 
        },
        meat: {
            beef: 1000,
            chicken: 2000
        }
    }
},{
    food: {
        fruits: {
            apples: 4,
            bananas: 5,
            peaches: 'triangle',
            citrus: [101,201,301] 
        },
        meat: {
            beef: 1001,
            chicken: 2001
        }
    }
}];

let output = {
    food: {
        fruits: {
            apples: [2,4],
            bananas: [3,5],
            peaches: ['square', 'triangle'],
            citrus: [[100,101],[200,201],[300,301]]
        },
        meat: {
            beef: [1000, 1001],
            chicken: [2000, 2001]
        }
    }
}

It appears that there isn't a specific function available in the API for this task. I am curious if there is a way to achieve this in one iteration without needing to loop through the initial collection multiple times.

Answer №1

To achieve the desired output, you can utilize the mergeWith() method in the following manner:

const output = _.mergeWith({}, ...input, (target, source) => {
  if (!_.isObject(source)) return target ? [...target, source] : [source]
});

const input = [{
  food: {
    fruits: {
      apples: 2,
      bananas: 3,
      peaches: 'square',
      citrus: [100, 200, 300]
    },
    meat: {
      beef: 1000,
      chicken: 2000
    }
}, {
  food: {
    fruits: {
      apples: 4,
      bananas: 5,
      peaches: 'triangle',
      citrus: [101, 201, 301]
    },
    meat: {
      beef: 1001,
      chicken: 2001
    }
}]};

const output = _.mergeWith({}, ...input, (target, source) => {
  if (!_.isObject(source)) return target ? [...target, source] : [source]
});

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

This code snippet will generate the exact desired output once any input inconsistencies are rectified:

{
  "food": {
    "fruits": {
      "apples": [2, 4],
      "bananas": [3, 5],
      "peaches": ["square", "triangle"],
      "citrus": [[100, 101], [200, 201], [300, 301]]
    },
    "meat": {
      "beef": [1000, 1001],
      "chicken": [2000, 2001]
    }
  }
}

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

Utilize AngularJS to modify the appearance of text

Just starting out with AngularJS and I need to achieve the following task. I have a text that says "bob" and two buttons, one for bold and one for italic. When the bold button is clicked, I want to make the text BOB bold and when the italic button is click ...

Website experiences technical difficulties but database remains up-to-date

I previously made a similar post, but I have not resolved the issue yet. Here is the output from my terminal: 23 Dec 22:31:23 - Serving request for url[GET] /team 23 Dec 22:31:23 - Successfully created team with Name : Japan 23 Dec 22:31:23 - Serving re ...

Function parameter accepting an anonymous value object

While working with prisma nexus and examining the prismaObjectType, I came across something unusual. A simple example of this is as follows: In a basic function, demo(p), the parameter p should be an object. function demo(p) { console.log(p); con ...

Fluctuating Visibility with Jquery Show()

<html> <head> <script type="text/javascript"> var oauth = chrome.extension.getBackgroundPage().oauth; </script> <style type="text/css"> #note { display:none; } </style> <script src="Task.js" type="text/javascript"> ...

Reveal/Conceal footer upon vertical scrolling

I am attempting to achieve the following goals: Display the div element when the scrolling position is greater than 20 Apply a fadeOut effect after a certain delay Prevent the fadeOut effect when hovering over the sticky footer This is my implementation ...

What is the best method for transferring formatted text from the clipboard to an HTML textarea?

When you copy and paste from a web browser to a text processor, the HTML markup gets converted to rich text. The text processor then tries to convert this markup into its own format, proving that the Clipboard can hold markup. However, when you copy and p ...

What is causing my JavaScript not to load properly within Bootstrap tabs?

I am facing an issue with my website which has Bootstrap 4 tabs implemented in a blade template. The problem arises when there are tabs within tabs, and upon clicking one tab, the slicks Javascript plugin that I created does not load on other tabs. It on ...

Tips for substituting commas and slashes within an input text box

For instance, if the input is "1,23/456", the output should be "123456". When "1,23/456" is entered into the input field and "enter" is pressed, it should automatically convert to "123456". <input id="Id" ng-model="Id" name="searchInput" type="text"&g ...

Hold off on addressing the nested loops within a TypeScript subscription

Goal: Ensure all nested loops complete processing before returning final value. Problem: Final value returned prematurely, before completion of loop processing. In the code snippet below, I am sending paramListToComplete to a data service for creating a ...

Utilize JavaScript array to filter, match, and perform calculations based on dates and names

I am working with the following dataset: const data = [ { "employee_name": "Employee A", "commission_date": "14/05/2018", "commission_price": 9000 }, { "employee_name": "Employee A", "commission_date": "17/05/2018", "commissi ...

Django Website Experiencing Issues with Google Analytics Integration

I implemented google analytics by inserting the tracking script tag and code at the bottom of the head section in my base.html template which serves as the foundation for all other pages. Additionally, I set up 2 click events to track when users click on ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

What is the correct way to implement fetch in a React/Redux/TS application?

Currently, I am developing an application using React, Redux, and TypeScript. I have encountered an issue with Promises and TypeScript. Can you assist me in type-defining functions/Promises? An API call returns a list of post IDs like [1, 2, ..., 1000]. I ...

Preventing duplicate submissions with an onclick button: Here's how

processApproval = (item) => { const {approve} = this.state; let {errors} = this.state; if (!isUndefined(approve.text)){ if (approve.text.length > 0){ this.setState({loading: true}); ...

The console is displaying a state that has not been updated in the Redux reducer yet

I am currently facing a puzzling issue that I can't quite pinpoint whether it's related to Chrome console, Redux, or JavaScript objects. Within my React + Redux application, I have the following function: function InputReducer(state = [{ }], ac ...

Personalized information boxes for particular data points within highcharts

When hovering over specific points, I want to display unique warnings or explanations in the tooltip. I have included custom text like 'WARNING' and 'WARNING 2' within the series data but am struggling to retrieve that data for each too ...

Error: Node.js/Express unable to connect to static assets

I recently deployed my Express application to a production server and encountered an issue with serving static assets. All of my assets are located in the /public directory, and I am using the following code to call the static middleware: // config.root ...

What is the process for passing parameters to a Node.js script when using PHP exec()?

I have encountered an issue with implementing iOS push notifications. My PHP version has ceased functioning, and despite my efforts to troubleshoot and fix it, I have been unsuccessful in getting it operational again. However, I do have a node.js script th ...

Exploring the capabilities of React testing-library for interacting with the DOM within a React application

I've been working on developing custom developer tools after finding inspiration from Kent C Dodds' insightful article here. One of the challenges I encountered was automatically populating values in a form that I created. My approach involved u ...

Anticipated request for spy navigation with path '/members' was expected, but unfortunately was not triggered

I am facing an issue with a service method that performs an HTTP delete operation. The expected behavior is that upon successful deletion, the page should be redirected to another location. However, during testing, I noticed that the router navigation func ...