Leverage lodash operators within nested object properties

My data consists of an array of objects

{
  "agent_name": "AgentName",
  "analytics": [
    {
      "date": "Tue, 1 Aug 2021 00:00:00 GMT",
      "intents_count":[
         {
           "count": 5,
           "intent": "intent1"
         },
         {
          "count": 1,
          "intent": "intent2"
         },
         {
           "count": 0,
           "intent": "intent3"
         },
       ]
    },
    {
      "date": "Tue, 2 Aug 2021 00:00:00 GMT",
      "intents_count":[
         {
           "count": 5,
           "intent": "intent1"
         },
         {
          "count": 1,
          "intent": "intent2"
         },
         {
           "count": 0,
           "intent": "intent3"
         },
       ]
    },
    ... and so on for the remaining days of the month
  ]
}

I am seeking to calculate the cumulative sum of counts for each intent, grouped by date.

The desired output would be:

[10, 2, 0]

This means that 10 corresponds to the total count for 'intent1' across all days.

Answer №1

To retrieve the final output, it is necessary to flatten and choose the specific array called "analytics". Subsequently, apply groupBy and sum operations to obtain the desired outcome.

let data = {
  "agent_name": "AgentName",
  "analytics": [
    {
      "date": "Tue, 1 Aug 2021 00:00:00 GMT",
      "intents_count":[
         {
           "count": 5,
           "intent": "intent1"
         },
         {
          "count": 1,
          "intent": "intent2"
         },
         {
           "count": 0,
           "intent": "intent3"
         },
       ]
    },
    {
      "date": "Tue, 2 Aug 2021 00:00:00 GMT",
      "intents_count":[
         {
           "count": 5,
           "intent": "intent1"
         },
         {
          "count": 1,
          "intent": "intent2"
         },
         {
           "count": 0,
           "intent": "intent3"
         },
       ]
    },
  ]
}

let flatRes = _.flatMap(data.analytics, 'intents_count');
let res = _(flatRes).groupBy('intent').map(x => _.sumBy(x, 'count'));
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Answer №2

My approach provides a high-level solution to the problem at hand. While I don't rely on lodash operators, this method serves as a solid starting point for further development.

const data = {
  "agent_name": "AgentName",
  "analytics": [{
      "date": "Tue, 1 Aug 2021 00:00:00 GMT",
      "intents_count": [{
          "count": 5,
          "intent": "intent1"
        },
        {
          "count": 1,
          "intent": "intent2"
        },
        {
          "count": 0,
          "intent": "intent3"
        },
      ]
    },
    {
      "date": "Tue, 2 Aug 2021 00:00:00 GMT",
      "intents_count": [{
          "count": 5,
          "intent": "intent1"
        },
        {
          "count": 1,
          "intent": "intent2"
        },
        {
          "count": 0,
          "intent": "intent3"
        },
      ]
    }
  ]
}

const arr = [];

data.analytics.forEach(intentObj => {
  intentObj.intents_count.forEach(obj => {
    //calculating the index to store the value in array.
    const index = obj.intent[6] - 1;
    if (arr[index] !== undefined) {
      arr[index] = arr[index] + obj.count;
    } else {
      arr[index] = obj.count;
    }
  });
});

console.log(arr);

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

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

Explore various THREE.JS 3D models through a clickable link

I am struggling to make each object open a new page using a URL when clicked. No matter what I try, it doesn't seem to work properly. Can someone point out what I might be missing or doing wrong? Here is the click event code for the objects. If needed ...

Loading background images in CSS before Nivo slider starts causing a problem

I've been struggling with preloading the background image of my wrapper before the nivo-slider slideshow loads. Despite it being just a fraction of a second delay, my client is quite particular about it -_- After attempting various jQuery and CSS tec ...

What is causing this error/bug to show up in Angular?

I encountered an error while working on my Angular project that incorporates both front-end and back-end development with Python Flask. Even though the page updates correctly, a database-related error is being displayed in the console. Below are the snippe ...

Using Angularjs to dynamically generate and submit tables

I can't seem to figure out this specific situation Data: $scope.MyItem = [ { "__v": 0, "myItemId": "55ed819caefe18e81ffbd2d2", "itemId": "56fec8abb192c870117ed393", "january": 1, "february": 1, ...

Test an express + sequelize server using chai-http ping command

Currently facing challenges while setting up tests using Express and Sequelize. The testing framework being used is Mocha + Chai. Initially, only a ping test is being attempted. The code snippet from server.js: const express = require('express&apos ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

Associating mongoose object with a DTO object in an Express.js application

I am looking for a way to transform mongoose result objects into DTOs for my views. Here is an example query that returns a mongoose object: const returnedData = (err, result) => { //Result object is a schema from Moongose cb(err, re ...

Implementing character limits in VueJS fields

new Vue({ el: '#app', data() { return { terms: false, fullname:'', maxfullname: 10, mobile: '', maxmobile: 10, area: '', maxarea: 12, city: '', ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

A bot responsible for assigning roles never fails to remove a role when necessary

My goal was to develop a bot that automatically assigns users a role based on the language they speak in a bilingual server. However, when I tried to assign myself the Czech role, it added the role but failed to remove the rest: const Discord = require(&a ...

Is there a way to show output on render rather than using console.log in node.js?

I have successfully sorted the objects as shown in the link below. My next challenge is to integrate the sorted object into my render function rather than just using console.log(). I'm uncertain if converting it back into an object is the right appro ...

Loop through an array of items and use the preg_match_all function to find matches for each item

I am currently working on modifying Interspire Email code. The program is set up to analyze the HTML content of emails before sending them, specifically looking for 'a href' links to replace. However, I would like to expand this functionality to ...

Navigating to a new link containing query parameters

I am working on setting up a redirect in Angular 6 The process for the redirect is quite simple as outlined below: Obtain destination URL from parameters: this.returnUrl = this.route.snapshot.queryParams['route'] || '/'; Perform Red ...

Next.js is constantly fetching data with React Query

Within my Next.js project, I incorporated a query client into a page component, utilizing getServerSideProps for server-side rendering. The structure of the page is as follows: const Index = ({ configData }) => { const { t } = useTranslation(); cons ...

When the model is replaced, the Vue.js directive v-html may fail to update

Upon running the code below (a Vue.js component), my expectation is that both the v-html directive and the console.log() will display the same value after the AJAX call returns. To my surprise, while v-html remains stuck at "loading...(1)", the value of o ...

Transferring a variable between a JavaScript function and a Java class

Currently, I am working with STS and building an application that includes HTML files and JavaScript. Within this file, there is a function that configures variables. <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

An error occurs when attempting to assign a value to a MUI file TextField

Struggling with setting the value of a MUI Textfield that has type="file" props, resulting in the following exception being thrown: Uncaught DOMException: An attempt was made to use an object that is not, or is no longer, usable Interest ...

Filter out any empty properties in JavaScript ajax formData

Need help with excluding empty fields from form data when sending via JavaScript Does anyone know how to prevent empty fields[] from being included in the formData sent through JavaScript? Desired Header Output fields[name]: name fields[phone]: phone ...