Using lodash to combine the values of identical objects

As a newcomer to development, I am looking to group similar objects within an array of JSON objects. Here is an example of my JSON array:

var data = [
    {
        zone: "Bottom",
        group: "Bottom girders",
        original: 7,
        gauge: 3,
        dPercent: 0,
        permissible: 10,
    },
    ...
];

The desired final output is:

[
      {
        "zone": "Neutral Axis",
        "groups": [...]
      },
      {
        "zone": "Bottom",
        "groups": [...]
      }
    ]

I aim to organize the data by zone, then within each zone by different group, and display the summed up values for original and gauge as shown in the final output.

If you'd like to see the code I have been working on, please visit this link:

Thank you very much in advance!

Answer №1

Based on the output example provided, it appears that you are looking to group your entities by their zone property and obtain the result as an array.

Here is the code snippet that accomplishes this:

var data = [/*your data here*/];

var groupedData = _.groupBy(data, 'zone');
var result = _.map(groupedData, (value, key) => {
  return {
    "zone": key,
    "groups": value
  }
});

If you prefer chaining methods, you can achieve the same result like this:

var result = _.chain(data)
  .groupBy('zone')
  .map((value, key) => {
    return {
      "zone": key,
      "groups": value
    }
  }).value();

The _.groupBy function converts your data array into an object structured like this:

{
   "Bottom":[
      /* All entities with zone "Bottom" */
   ],
   "Neutral axis":[
      /* All entities with zone "Neutral axis" */
   ]
}

Subsequently, we convert this object into an array of objects according to your specifications using _.map.

Additional Resources:

https://lodash.com/docs/4.17.15#groupBy

https://lodash.com/docs/4.17.15#map

https://lodash.com/docs/4.17.15#chain

Answer №2

Essentially, what you're looking for is:

  1. Firstly, group by the zone attribute
  2. Then within each group, further group by the group attribute
  3. For each group, have the zone as a key and an array of nested groups under the groups key
  4. Within each nested group, include the zone, group values directly, and sum up the other 4 attributes (referred to as original) for that nested group

Let's achieve this easily with the following code snippet:

const data = [{"zone":"Bottom","group":"Bottom girders","original":7,"gauge":3,"dPercent":0,"permissible":10},{"zone":"Bottom","group":"Bottom girders","original":9,"gauge":7,"dPercent":0,"permissible":10},{"zone":"Bottom","group":"risers","original":7,"gauge":3,"dPercent":0,"permissible":10},{"zone":"Neutral axis","group":"Transverse PSM","original":17,"gauge":28,"dPercent":0,"permissible":15},{"zone":"Neutral axis","group":"Transverse PSM","original":17,"gauge":12,"dPercent":0,"permissible":15}];

var res = _(data)
    .groupBy('zone')
    .map((grp, zone) => ({
        zone,
        groups: _(grp).groupBy('group').map((nestGrp, group) => ({
            zone,
            group,
            original: _.sumBy(nestGrp, 'original'),
            gauge: _.sumBy(nestGrp, 'gauge'),
            dPercent: _.sumBy(nestGrp, 'dPercent'),
            permissible: _.sumBy(nestGrp, 'permissible')
        })).value()
    })).value();
    
 console.log(res);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8083888d9f84acd8c2dddbc2dedd">[email protected]</a>/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

What is the method for calling a JavaScript function from one file to another within a Node.js environment?

Just starting out with JavaScript and exploring the idea of breaking the code into multiple modules. While working with nodejs, I've encountered an issue where it's complaining about pathChecker not being defined. Any insights on how to resolve t ...

What is the best way to change a canvas into an image while preserving transparency?

Currently, I am attempting to modify a weather radar image with a black background by making the background transparent using canvas. However, when I view the modified image, instead of transparency, the background now appears as a red and black checkerboa ...

Adorn your restify rendering

Having trouble enhancing the render function in restify's router using this code... enhance.js module.exports = function (server) { return function (req, res, next) { function customRender(original) { return function(path, pa ...

What is the best way to arrange a list in Angular2 using AngularFire2's FirebaseListObservable?

Looking to retrieve all users from a Firebase realtime database and organize them based on a score property. I managed to achieve this by using the variable users: FirebaseListObservable<any[]>; however, encountered the following errors: Type & ...

"Exploring the world of arrays and looping in

Can someone assist me with this issue? I am currently stuck in JS Arrays & Loops and I can't understand why it's not returning "0" when the function is empty. function sumArray (numbers) { // your code var numbers = [1, 2, 3, 4]; if (nu ...

Is it possible to pass props in React-Native without relying on the navigator component

Is there a way to pass properties to a webview without using navigator? I am working on updating the source for a WebView in my index.ios.js file while keeping the song playing throughout the app. In my index.ios.js, I have an invisible iframe that allows ...

What is the best way to surround the initial x words within an element with a span tag?

Is there a way to style the first 10 words of a paragraph in a different color when the content is constantly changing? I can't manually add a span in the HTML. My approach involves using JavaScript to iterate through all instances of .overview__text. ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

Angular Material Progress Spinner is static and not animated

I've been attempting to incorporate an indeterminate spinner from Angular Material. After reviewing the stack blitz example provided on their official website https://stackblitz.com/angular/nkabnxaenep, I carefully compared the package jsons and could ...

Can a hyperlink exist without a specified href attribute?

One scenario could be when I receive this specific code from a third-party source <a class="cs_import">Add contacts from your Address Book</a> Curiously, the link "Add contacts from your Address Book" does not redirect to any page as expected ...

Persistent column menu in ag-grid

Is there a way to include a menu for each row within a sticky column in Ag-grid? I couldn't find any information about this feature in the official documentation, so I'm unsure if it's even possible. I've attempted several methods, but ...

Error: The array contains an undefined image object

Currently, I am implementing a simple image preloading technique using promises. This function is integrated into a larger Angular (1.3.15) custom directive. Here is the JavaScript code snippet: function preLoad() { var deferred = $q.defer(); ...

Could someone provide me with a breakdown of this code utilizing the .bind() function?

The code snippet above is from the jQuery source code and it deals with event handling. It defines an array of events, such as click, focus, blur, etc., and then adds each event to the jQuery prototype using a forEach loop. var events = ['click', ...

Delay the execution in selenium webdriver using Java until the login button is clicked manually

Can Selenium Webdriver be used to pause code execution with webdriver.wait until the user clicks the login button on a form? The form includes a Captcha that requires manual input, preventing automated clicking of the button by the script. Clicking the log ...

Prevent parent element from triggering double click when double clicking on children element with CSS or jQuery

Check out my project demo here Whenever I double click on a child element, it also triggers the parent element at the same time. I want to prevent this behavior so that only the child element is affected by the double click event. Can anyone provide assis ...

The content located at “http://localhost:3000/public/static/” was restricted because of a mismatch in MIME type (text/html) which triggered the X-Content-Type-Options:nosniff protocol

https://i.stack.imgur.com/7Etn7.png Every time I try to run the server with nodemon, I keep encountering the error mentioned in the title. Below is the code snippet from the JavaScript file: const express = require('express') const path = requir ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Do NodeJS and Express require sanitizing the request body for post requests to prevent cross-site scripting (XSS) attacks?

There is a website I have where users can input data into fields and submit it. Once submitted, the information is sent to my server through a POST request and saved in the database. However, this user-generated content is also returned to the front-end f ...

Tips for retrieving data from a Node.js server with a POST request in a React application

I'm currently working on a MERN authentication project, but I've hit a roadblock. Whenever the information is submitted on my register page, it triggers an add user function on the front end. async function addUser(user) { const config = { ...

Sending an array containing a mix of data types from PHP to a JavaScript array

I am facing a problem with my asynchronous / getJSON implementation. I have an array loaded from a MySQL database in a PHP file called "loadblocks.php" and I have verified that the output is correct by echoing json_encode($content). The data is being print ...